ASP.NET Core WebApi HttpResponseMessage创建自定义消息吗? [英] ASP.NET Core WebApi HttpResponseMessage create custom message?
问题描述
如何在ASP.NET Core WebApi中创建自定义消息? 例如,我想返回
How can I create custom message in ASP.NET Core WebApi ? For example I want to return
new HttpResponseMessage()
{
StatusCode=HttpStatusCode.OK,
Message="Congratulations !!"
};
new HttpResponseMessage()
{
StatusCode=HttpStatusCode.NotFound,
Message="Sorry !!"
};
推荐答案
此最简单的方法是使用基础Controller类中的帮助程序.
This simplest method is to use the helpers from the base Controller class.
public ActionResult ExampleNotFound()
{
return NotFound("Sorry !!");
}
public ActionResult ExampleOk()
{
return Ok("Congratulations !!");
}
或者,您可以返回一个新的ContentResult
并设置其状态代码.
Alternatively you can return a new ContentResult
and set it's status code.
return new ContentResult
{
Content = "Congratulations !!",
ContentType = "text/plain",
StatusCode = 200
};
这两种方法略有不同,ContentResult
将始终具有text/plain
的ContentType
These two methods are slightly different, the ContentResult
will always have a ContentType
of text/plain
Ok()
和NotFound()
方法返回一个ObjectResult
,它使用格式化程序根据请求中Accept头中的内容类型对字符串进行序列化.
The Ok()
and NotFound()
methods return an ObjectResult
which uses a formatter to serialize your string according to the content types in the Accept header from the request.
这篇关于ASP.NET Core WebApi HttpResponseMessage创建自定义消息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!