c# - 无法在 asp vNext 中修改 HttpResponse 对象上的原因短语

标签 c# asp.net asp.net-core http-response-codes

我必须在我的 asp 5 中间件中设置原因短语,而不仅仅是 http 响应消息的状态代码,但我找不到任何方法来做到这一点。 Microsoft.AspNet.Http.HttpResponse 类的 StatusCode 属性是一个 int 属性,仅用于修改状态代码,而不是原因文本.

我知道,原因是根据状态代码自动设置的,但在我的情况下,我必须将其设置为自定义值。根据 HTTP RFC 2616 哪个没问题:

[..] The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol. [..]

我目前正在使用 beta-8 版本的 asp 5 框架。

最佳答案

你可以试试:

Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "some reason";

同时返回原因的 HttpStatusCodeResult 可能如下所示:

public class BadRequestResult : HttpStatusCodeResult
{
    private readonly string _reason;

    public BadRequestResult(string reason) : base(400)
    {
        _reason = reason;
    }

    public override void ExecuteResult(ActionContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = _reason;
        context.HttpContext.Response.StatusCode = StatusCode;
    }
}

关于c# - 无法在 asp vNext 中修改 HttpResponse 对象上的原因短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33695224/

相关文章:

c# - 防止 "' System.DateTime' 失败,因为物化值为 null"

c# - TripleDES 16 字节不工作

asp.net - 如何 ping 诸如 svc、asmx 之类的 Web 服务

c# - 同一应用程序中的多个静态变量范围?

c# - 如何将复选框列表的多个值传递给代码后面的存储过程?

asp.net - 如何对 ASP.NET 应用程序进行负载测试?

asp.net - .NET 4 web.config 文件重构 - 有什么值(value)?

c# - StackExchange.Redis.RedisTimeoutException - 由于问题人们如何解决它?

c# - asp.net 核心默认代理

entity-framework - 升级到 2.1 破坏了现有的 .net core EF 逻辑