【问题标题】:ASP.NET MVC handle request errorASP.NET MVC 处理请求错误
【发布时间】:2016-04-15 15:10:40
【问题描述】:

在我的 .Net MVC 应用程序中,我需要处理服务器端验证。如果请求有问题,我会得到:

{
   "validationMessage": message
}

StatusCode = 200。 否则,我当然会得到适合通话的响应。我的问题是我在检查验证消息然后反序列化响应时遇到了麻烦(尽管提琴手告诉我响应回来了,但我总是在那里得到 null)。

 public static async Task<Response<T>> Response<T>(HttpResponseMessage response)
    {
        var res = new Response<T>();

        if (response.IsSuccessStatusCode)
        {
            //check for validation messages
            var serverErrorInfo = await response.Content.ReadAsAsync<ServerError>();
            if (serverErrorInfo.ValidationMessage != null)
            {
                res.ErrorInfo = new ErrorInfo(serverErrorInfo.ValidationMessage);
            }
            else
            {
                var result = await response.Content.ReadAsAsync<T>();
                res.IsSuccess = true;
                res.Result = result;
            }
            return res;
        }

我做错了什么?在第一次尝试将其读取为 ServerError 后,响应是否会被处理?因为我使用泛型,所以我不能先检查是否有响应,然后再阅读验证消息。
服务器错误代码:

 [JsonObject]
public class ServerError
{
    public string validationMessage{ get; set; }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    可能是反序列化问题。您是否尝试过在 json 响应中使用大写 V 的 ValidationMessage?此外,serverErrorInfo 是完全为空,还是只是属性 ValidationMessage 为空?你能在反序列化为 ServerError 之前检查 response.Content 的值吗?

    【讨论】:

    • 不幸的是,整个 ServerErrorInfo 对象为空。一旦我在没有条件的情况下切换了订单(首先作为响应对象读取,然后作为我故意创建错误请求的错误)。内容不会被反序列化为响应(这很明显,因为没有什么可以反序列化,但也不会反序列化状态消息。使用大小写也没有帮助。当我尝试 ReadAsAsync 时的内容长度为 36指出验证消息必须存在。
    【解决方案2】:

    最终解决方案只是使用了一些丑陋的代码:

    var serverErrorInfo = JsonConvert.DeserializeObject<ServerError>(await response.Content.ReadAsStringAsync());
    

    我很不确定为什么 ReadAsAsync 会在那里失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      相关资源
      最近更新 更多