在我的 .Net MVC 应用程序中,我需要处理服务器端验证。如果请求有问题,我会得到以下信息:
{
"validationMessage": message
}
状态代码 = 200。 否则,我当然会得到正确的调用响应。我的问题是,我在检查验证消息然后反序列化响应时遇到麻烦(尽管 fiddler 显示响应返回,但我总是得到 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; }
}
最佳答案
可能是反序列化问题。您是否尝试过在 json 响应中使用大写 V 的 ValidationMessage ?另外,serverErrorInfo 是完全为空,还是只是属性 ValidationMessage 为空?您能在反序列化为 ServerError 之前检查一下 response.Content 的值吗?
关于c# - ASP.NET MVC 处理请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36624797/