jum*_*791 7 c# rest asp.net-web-api asp.net-core
如何在ASP.NET Core WebApi中创建自定义消息?例如,我想回来
new HttpResponseMessage()
{
StatusCode=HttpStatusCode.OK,
Message="Congratulations !!"
};
new HttpResponseMessage()
{
StatusCode=HttpStatusCode.NotFound,
Message="Sorry !!"
};
Run Code Online (Sandbox Code Playgroud)
这个最简单的方法是使用基类Controller类的助手.
public ActionResult ExampleNotFound()
{
return NotFound("Sorry !!");
}
public ActionResult ExampleOk()
{
return Ok("Congratulations !!");
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以返回一个新的ContentResult并设置它的状态代码.
return new ContentResult
{
Content = "Congratulations !!",
ContentType = "text/plain",
StatusCode = 200
};
Run Code Online (Sandbox Code Playgroud)
这两种方法都略有不同,ContentResult总会有一个ContentType中text/plain
该Ok()和NotFound()方法返回一个ObjectResult,它使用格式化根据来自请求的Accept头的内容类型序列化的字符串.
为了返回legacy HttpResponseMessage,您需要将其转换为ResponseMessageResult.net core。下面是一个例子。
public async Task<IActionResult> Get(Guid id)
{
var responseMessage = HttpContext.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK,
new YourObject()
{
Id = Id,
Name = Name
});
return new ResponseMessageResult(responseMessage);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16643 次 |
| 最近记录: |