返回 HttpStatusCode 202 以及字符串值

the*_*ner 5 c# http-response-codes asp.net-core asp.net-core-webapi

我希望返回 202 - HttpStatusCode.Accepted - 以及一个字符串值。

这怎么写:

[HttpPost]
public async Task<IActionResult> Post()
{

    return Accepted(); //+ "my string value"

}
Run Code Online (Sandbox Code Playgroud)

Ily*_*kov 6

使用通用StatusCode方法:

return StatusCode((int)HttpStatusCode.Accepted, obj);
Run Code Online (Sandbox Code Playgroud)

Content-Type如果需要,可以设置响应标头。JsonResult然而,使用返回 JSON更容易:

return new JsonResult(obj)
{
    StatusCode = (int)HttpStatusCode.Accepted
};
Run Code Online (Sandbox Code Playgroud)

或者甚至使用ObjectResult来获得完全控制:

return new ObjectResult(xml)
{
    StatusCode = (int)HttpStatusCode.Accepted,
    ContentTypes = new MediaTypeCollection { MediaTypeHeaderValue.Parse("application/xml") }
};
Run Code Online (Sandbox Code Playgroud)