【问题标题】:Asp.net 5 web api return status code and bodyAsp.net 5 web api 返回状态码和正文
【发布时间】:2016-07-11 13:48:54
【问题描述】:

我正在使用 ASP.NET 5 开发一个项目,并且正在编写一个 web api。

我继承了一些代码和数据库存储过程,它们使用 raiserror 来指示出现问题(用户名/密码不正确、许可证过期等)。

存储过程不返回任何内容来唯一标识该错误,除了消息文本。

我希望能够返回 HTTP UNAUTHORIZED 响应,同时也将错误消息传递给客户端。

内置的IActionResult HttpUnauthorized() 方法不允许给出理由。

所以我编写了自己的 ActionResult,如下所示:

public class UnauthorizedWithMessageResult : IActionResult
{
    private readonly string _message;

    public UnauthorizedWithMessageResult(string message)
    {
        _message = message;
    }

    public async Task ExecuteResultAsync(ActionContext context)
    {
        using (var sw = new HttpResponseStreamWriter(context.HttpContext.Response.Body, Encoding.UTF8))
        {
            await sw.WriteLineAsync(_message);
        }

        await new HttpUnauthorizedResult().ExecuteResultAsync(context);
    }
}

问题是客户端收到 200-OK 就好像一切正​​常。

我已经完成了这个,在完成对HttpUnauthorizedResult 的委托后,状态码确实设置为 403。

看起来 Web API(在某些时候)看到响应正文中有内​​容,并确定这意味着一切正常并重置状态代码。

有什么办法可以绕过这个问题,而不必求助于将消息作为标题或其他东西发送? (或者这是正确的方法吗?)

【问题讨论】:

  • 写完响应正文的任何​​部分后,您都无法设置状态码。您是否尝试在编写消息之前调用 HttpUnauthorizedResult.ExecuteResultAsync?
  • 看来这个链接可以解决你的问题weblogs.asp.net/gunnarpeipman/…
  • @Gomes 看起来很有前途!我想从概念上讲它是有道理的,应该尽快看看!
  • @Gomes 不幸的是,这并不能解决我的问题,StatusDescription 属性不再是一个东西......

标签: c# asp.net-web-api2 asp.net-core


【解决方案1】:

你可以这样做:

return new ObjectResult("The message") { 
    StatusCode = (int?) HttpStatusCode.Unauthorized 
};

【讨论】:

    【解决方案2】:

    它是这样工作的:

    public IActionResult IWillNotBeCalled()
    {
        return new UnauthorizedWithMessageResult("MY SQL ERROR");            
    }
    
    public class UnauthorizedWithMessageResult : IActionResult
    {
        private readonly string _message;
    
        public UnauthorizedWithMessageResult(string message)
        {
            _message = message;
        }
    
        public async Task ExecuteResultAsync(ActionContext context)
        {
            // you need to do this before setting the body content
            context.HttpContext.Response.StatusCode = 403;
    
            var myByteArray = Encoding.UTF8.GetBytes(_message);
            await context.HttpContext.Response.Body.WriteAsync(myByteArray, 0, myByteArray.Length);
            await context.HttpContext.Response.Body.FlushAsync();
        }
    }
    

    您必须在设置正文之前设置StatusCode,并且您必须刷新正文流以确保将在响应中设置内容。

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      你可以返回任何你想要的状态码,像这样:

      return new HttpStatusCodeResult(403);
      

      【讨论】:

      • 问题不在于状态码,而是在响应正文中添加了一些文本以及被证明具有挑战性的状态码。
      猜你喜欢
      • 1970-01-01
      • 2016-04-23
      • 2018-04-27
      • 2020-11-10
      • 2021-09-24
      • 2016-04-23
      • 1970-01-01
      • 2013-12-04
      • 2017-04-23
      相关资源
      最近更新 更多