【问题标题】:Add Json response in C#.net API for all scenarios在 C#.net API 中为所有场景添加 Json 响应
【发布时间】:2019-07-29 23:01:06
【问题描述】:

我如何始终返回 Json 响应,HTTP 代码是否需要为 200、401 或其他都无关紧要。

对于 HTTP 200,Json 使用 return Ok(response); //where response is a model. 发送 对于 HTTP 401(未经授权),我有以下内容:

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent(msg),
                    ReasonPhrase = msg
                });

但是 msg 需要是一个字符串...我无法让它与模型一起返回 JSON。

BadRequest 或其他 HTTP 状态也会发生同样的情况。

【问题讨论】:

    标签: c# asp.net .net


    【解决方案1】:

    没有人说StringContent的内容不能是序列化对象。 试试这个:

    // uses Newtonsoft.Json
    var serializedString = JsonConvert.SerializeObject(yourObject);
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
        Content = new StringContent(serializedString, System.Text.Encoding.UTF8, "application/json"),
        ReasonPhrase = msg
    });
    

    归功于Put content in HttpResponseMessage object?

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多