如何使用状态和文本消息返回HttpResponseException

问题描述

我有这个:

    [HttpDelete] 
    public HttpResponseMessage DeleteClient(int idCliente)
    {
     

        return new HttpResponseMessage(HttpStatusCode.OK);

    }

如何在状态旁边返回消息文本?

解决方法

为什么您的主题中有HttpResponseException?如果确实需要在引发异常时返回错误状态代码和消息,则HttpResponseException的构造函数将使用HttpResponseMessage实例。

但是在.NET Core中,仅在Microsoft.AspNetCore.Mvc.WebApiCompatShim向后兼容程序包中存在该异常。推荐的方法是直接返回带有错误状态代码的HttpResponseMessage

,

您可以执行以下操作:

return new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StringContent("The Message")
};

如果要返回JSON(使用Newtonsoft.Json库),可以执行以下操作:

return new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StringContent(
        JsonConvert.SerializeObject(new { message = "The Message" }),Encoding.UTF8,"application/json")
};