c# – ASP.NET Core WebApi HttpResponseMessage创建自定义消息
发布时间:2020-12-15 23:37:15 所属栏目:百科 来源:网络整理
导读:如何在ASP.NET Core WebApi中创建自定义消息? 例如,我想回来 new HttpResponseMessage(){ StatusCode=HttpStatusCode.OK,Message="Congratulations !!"};new HttpResponseMessage(){ StatusCode=HttpStatusCode.NotFound,Message="Sorry !!"}; 解决方法 这
如何在ASP.NET Core WebApi中创建自定义消息?
例如,我想回来 new HttpResponseMessage() { StatusCode=HttpStatusCode.OK,Message="Congratulations !!" }; new HttpResponseMessage() { StatusCode=HttpStatusCode.NotFound,Message="Sorry !!" }; 解决方法
这个最简单的方法是使用基类Controller类的助手.
public ActionResult ExampleNotFound() { return NotFound("Sorry !!"); } public ActionResult ExampleOk() { return Ok("Congratulations !!"); } 或者,您可以返回一个新的ContentResult并设置它的状态代码. return new ContentResult { Content = "Congratulations !!",ContentType = "text/plain",StatusCode = 200 }; 这两种方法略有不同,ContentResult将始终具有text / plain的ContentType Ok()和NotFound()方法返回一个ObjectResult,它使用格式化程序根据请求的Accept标头中的内容类型序列化字符串. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |