我在每个API方法上都有相同的代码:
if (user.AspNetRoles.Where(p => p.Name == Models.Roles.SmartphonePhotographer).Count() == 0)
{
return Request.CreateResponse((HttpStatusCode)453, new { Message = "User does not have Smartphone Photographer role" });
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User does not have Smartphone Photographer role");
}
if (!user.EmailConfirmed)
{
return Request.CreateResponse((HttpStatusCode)454, new { Message = "User is not confirmed" });
}
并希望直接从覆盖Initialize方法返回Response。我可以做吗?
(当然,如果没有在Controller中设置用户变量,我已将其移至ActionFilter)
protected override void Initialize(HttpControllerContext controllerContext)
{
int id = controllerContext.RequestContext.Principal.Identity.GetUserId<int>();
user = controllerContext.Request.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(id);
base.Initialize(controllerContext);
}
答案 0 :(得分:1)
覆盖Initialize方法是一种void方法,因此您无法返回响应结果, 您应该在响应上写,但在Initialize方法中,响应仍未完成。 see this link
您可以重新路由到返回响应的方法,如下所示
IDE