如何返回一些附加数据的状态码401?

编程入门 行业动态 更新时间:2024-10-20 20:52:05
本文介绍了如何返回一些附加数据的状态码401?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写自定义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.

  • 对于Web API,如何返回状态代码401或403,以及 一些其他消息作为JSON有效负载?
  • 对于返回的MVC操作 HTML,我该如何返回状态代码401或403并重定向到其他URL?
  • 如何检查请求是WebAPI还是MVC 行动吗?
  • For Web API, How can I return status codes 401 or 403 along with some additional message as JSON payload?
  • For MVC Actions that return HTML, How can I return status codes 401 or 403 and redirect to different URL?
  • How can I check if the request is WebAPI or MVC action?
  • 推荐答案

    回答您的第一个问题,这就是授权属性的被覆盖方法的样子.错误消息将是状态消息,内容在响应正文中.

    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?

    本文发布于:2023-11-17 12:13:20,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1609964.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:状态   数据

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!