如何 return HttpResponseException 与状态和短信

How to return HttpResponseException with Status and text message

我有这个:

    [HttpDelete] 
    public HttpResponseMessage DeleteClient(int idCliente)
    {
     

        return new HttpResponseMessage(HttpStatusCode.OK);

    }

如何 return 状态旁边的消息文本?

你可以这样做:

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

如果你想 return JSON(使用 Newtonsoft.Json 库),你可以这样做:

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

为什么你的主题有 HttpResponseException?如果您确实需要在抛出异常时 return 带有消息的错误状态代码,HttpResponseException 有一个采用 HttpResponseMessage 实例的构造函数。

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