如何返回一些附加数据的状态码401? [英] How to return status code 401 along some additional data?

查看:379
本文介绍了如何返回一些附加数据的状态码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.

  1. 对于Web API,如何返回状态代码401或403,以及 一些其他消息作为JSON有效负载?
  2. 对于返回的MVC操作 HTML,我该如何返回状态代码401或403并重定向到其他URL?
  3. 如何检查请求是WebAPI还是MVC 行动吗?
  1. For Web API, How can I return status codes 401 or 403 along with some additional message as JSON payload?
  2. For MVC Actions that return HTML, How can I return status codes 401 or 403 and redirect to different URL?
  3. 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();).要重定向,您可以使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆