ASP.NET Core WebApi HttpResponseMessage创建自定义消息吗? [英] ASP.NET Core WebApi HttpResponseMessage create custom message?

查看:103
本文介绍了ASP.NET Core WebApi HttpResponseMessage创建自定义消息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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/plainContentType

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆