如何在asp.net core 2.1中设置带有自定义消息的状态代码?

Pra*_*ale 5 c# asp.net-core asp.net-core-webapi asp.net-core-2.1

我正在开发 asp.net core 2.1 版本,我创建了一个示例 API 项目,该项目工作正常,但我无法使用自定义消息修改状态代码,例如:

在邮递员中:

200 好

期待:

200 自定义消息

我尝试过的代码:

[HttpGet]
public IActionResult Get()
{
     Response.StatusCode = 200;
     Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Custom_Message";
     return Ok();
}
Run Code Online (Sandbox Code Playgroud)

邮递员当前的输出:

在此输入图像描述

GitHub Repository

ALF*_*LFA 1

我认为你应该创建你的自定义类:

public class CustomResult : OkResult
{
    private readonly string Reason;

    public CustomResult(string reason) : base()
    {
        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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器方法中:

[HttpGet]
public IActionResult Get()
{
     return new CustomResult("Custom reason phrase");
}
Run Code Online (Sandbox Code Playgroud)

输出

在此输入图像描述