我正在使用asp.net核心版本2.1,我创建了一个示例API项目,该项目可以正常运行,但是无法使用自定义消息修改状态代码,例如:
在邮递员中:
200好
期望:
200个Custom_Message
我尝试过的代码:
[HttpGet]
public IActionResult Get()
{
Response.StatusCode = 200;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Custom_Message";
return Ok();
}
邮递员的当前输出:
答案 0 :(得分:0)
我认为您应该创建自定义类:
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;
}
}
然后在您的控制器方法中:
[HttpGet]
public IActionResult Get()
{
return new CustomResult("Custom reason phrase");
}
答案 1 :(得分:0)
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
public abstract class BaseApiController : ControllerBase
{
public override OkResult Ok()
{
return base.Ok();
}
public override OkObjectResult Ok([ActionResultObjectValue] object value)
{
return base.Ok(new Response
{
Result = value,
Status = ResultStatus.Success,
Message = string.Empty
});
}
}