【问题标题】:How to return HttpResponseException with Status and text message如何返回带有状态和文本消息的 HttpResponseException
【发布时间】:2020-08-25 00:27:00
【问题描述】:

我有这个:

    [HttpDelete] 
    public HttpResponseMessage DeleteClient(int idCliente)
    {
     

        return new HttpResponseMessage(HttpStatusCode.OK);

    }

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

【问题讨论】:

    标签: asp.net asp.net-core-mvc webapi


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以这样做:

      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")
      };
      

      【讨论】:

      • JsonConvert 在当前上下文中不存在
      • @joeyanthon -- 你必须打开 Nuget 包管理器并找到 Newtonsoft.Json 并安装它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 2020-01-18
      • 2016-09-08
      • 1970-01-01
      相关资源
      最近更新 更多