[英]ASP.NET Core WebApi HttpResponseMessage create custom message?
How can I create custom message in ASP.NET Core WebApi ?如何在 ASP.NET Core WebApi 中创建自定义消息? For example I want to return
例如我想返回
new HttpResponseMessage()
{
StatusCode=HttpStatusCode.OK,
Message="Congratulations !!"
};
new HttpResponseMessage()
{
StatusCode=HttpStatusCode.NotFound,
Message="Sorry !!"
};
This simplest method is to use the helpers from the base Controller class. 这个最简单的方法是使用基类Controller类的助手。
public ActionResult ExampleNotFound()
{
return NotFound("Sorry !!");
}
public ActionResult ExampleOk()
{
return Ok("Congratulations !!");
}
Alternatively you can return a new ContentResult
and set it's status code. 或者,您可以返回一个新的
ContentResult
并设置它的状态代码。
return new ContentResult
{
Content = "Congratulations !!",
ContentType = "text/plain",
StatusCode = 200
};
These two methods are slightly different, the ContentResult
will always have a ContentType
of text/plain
这两种方法略有不同,
ContentResult
将始终具有text/plain
的ContentType
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. Ok()
和NotFound()
方法返回一个ObjectResult
,它使用格式化程序根据请求的Accept标头中的内容类型序列化字符串。
In order to return legacy HttpResponseMessage
, you need to convert it to ResponseMessageResult
in .net core. 为了返回遗留的
HttpResponseMessage
,您需要将其转换为.net核心中的ResponseMessageResult
。 The following is an example. 以下是一个例子。
public async Task<IActionResult> Get(Guid id)
{
var responseMessage = HttpContext.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK,
new YourObject()
{
Id = Id,
Name = Name
});
return new ResponseMessageResult(responseMessage);
}
Instead of CreateResponse You can use the StatusCode.您可以使用 StatusCode 代替 CreateResponse。 The StatusCode is in the namespace Microsoft.AspNetCore.Mvc .
StatusCode 位于命名空间Microsoft.AspNetCore.Mvc 中。 public virtual ObjectResult StatusCode([ActionResultStatusCode] int statusCode, [ActionResultObjectValue] object value) ;
public virtual ObjectResult StatusCode([ActionResultStatusCode] int statusCode, [ActionResultObjectValue] 对象值) ; Below is Synatax.
下面是 Synatax。 return StatusCode(Convert.ToInt32(returnstatus.StatusCode), senderResponse);
return StatusCode(Convert.ToInt32(returnstatus.StatusCode), senderResponse);
Return Type of Method will be IActionResult方法的返回类型将为 IActionResult
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.