我正在尝试编写自定义Authorize属性,以授权一些API端点和MVC操作.遵循此StackOverflow answer 之后,我编写了一个自定义属性.我正在使用UnauthorizedResult返回401.
I am trying to write a custom Authorize attribute to authorize some of the API endpoints and MVC actions. Following this StackOverflow answer, I wrote a custom attribute. I am using UnauthorizedResult to return 401.
推荐答案
回答您的第一个问题,这就是授权属性的被覆盖方法的样子.错误消息将是状态消息,内容在响应正文中.
Answering your first question, this is how overridden method of authorization attribute may look like. Error message will be status message and content is in response body.
public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) { string errorMessage = "User has no enough permissions to perform requested operation."; var httpContent = new StringContent("{ \"some\": \"json\"}", Encoding.UTF8, "application/json"); actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) { ReasonPhrase = errorMessage, Content = httpContent }; return Task.FromResult<object>(null); }从MVC动作中,您可以返回状态代码(如return StatusCode(418);)或使用专用方法(如return Unauthorized();).要重定向,您可以使用 RedirectToAction 或 context.Response.Redirect
From MVC action you can return status code like this return StatusCode(418); or using dedicated method like return Unauthorized();. To redirect you can use RedirectToAction or context.Response.Redirect
更多推荐
如何返回一些附加数据的状态码401?
发布评论