我应该尝试使用从API返回的BadRequest(ModelState),并使用JSON.NET反序列化为* what *吗? [英] Should I try to take BadRequest(ModelState) returned from my API, and deserialize to *what* with JSON.NET?
问题描述
TL; DR;
我喜欢我生成的AutoRest客户端在处理200个场景时如何反序列化我的主要实体.但是,我必须手动解析400个场景吗?",懒惰的程序员说.
"I like how my generated AutoRest client deserializes my main entities when dealing with the 200 scenarios.. but, MUST I manually parse the 400 scenarios?", said the lazy programmer
详细信息:
因此,我有一个API(Web API 2),并且我做了所有标准的工作.除了使用System.Data.DataAnnotations
进行属性级验证外,我还使用实现了IValidatable
的POCO,我的Web API返回了400个错误,例如这(只是一个例子):
So, I have an API, (Web API 2), and I do all the standard stuff.. using POCO's that implement IValidatable
in addition to property-level validation using System.Data.DataAnnotations
my Web API returns 400 errors like this (just an example):
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
而且,在适当的地方,我使用SwaggerResponse
属性,并记录了我的swagger.json,以便我生成的客户端知道400是一个可行的响应.
And, where appropriate I use SwaggerResponse
attributes, and my swagger.json is documented thus so that my generated client knows that a 400 is a viable response.
现在,我的单元测试直接实例化api控制器,我故意尝试测试无效的模型状态..我可以从控制器调用中获取IHttpActionResult
响应,并将其转换为InvalidModelStateResult
并遍历ModelState字典.
Now, my unit tests which directly instantiate the api controllers, I purposely try to test for invalid model state.. I can take the IHttpActionResult
response from the controller invocation, and cast it to InvalidModelStateResult
and iterate over the ModelState dictionary.
但是,我发现使用实际的HTTP客户端为我的生产HTTP调用"编写类似的内容-并不那么简单.
But, I find writing something similar for my 'production HTTP calls' with an actual HTTP client -- not as straightforward.
因此,离我的问题越来越近了:
So, getting closer to the heart of my question:
是否存在用于反序列化InvalidModelStateResult
的首选方法?
Is there a preferred method for deserializing the InvalidModelStateResult
?
因此,当通过Microsoft.Rest.ServiceClient
通过实际的http调用与我的API进行交互时.我返回的JSON的形状略有不同.
So, when interacting with my API with actual http calls.. via the Microsoft.Rest.ServiceClient
the JSON that I get back is in a slightly different shape..
与我的API交互的示例MVC控制器代码:
HttpOperationResponse resp = await client.SpecialLocations.PatchByIdWithHttpMessagesAsync(id, locationType, "return=representation");
if (!resp.Response.IsSuccessStatusCode)
{
//The JSON returned here is not really in the form of an InvalidModelStateResult
ViewBag.Error = await resp.Response.Content.ReadAsStringAsync();
return View(locationType);
}
推荐答案
所以,现在,我使用的是Newtonsoft的JObject
来解析从我的WebAPI返回的ModelState
(再次-一次检索时它的名称并没有这样的名称通过http请求),现在将其推送到我的MVC控制器的ModelState
.
So, for now, I'm using Newtonsoft's JObject
to parse ModelState
returned from my WebAPI (again - it's not really named as such once retrieved via http request) and now pushing it into my MVC controller's ModelState
.
这是我目前的回答.但是会考虑其他有任何优点的人.看来这是一件很奇怪的事情.
This is my answer for now. But will consider others that have any merit. It just seems like a weird thing to have to do.
HttpOperationResponse resp = await client.SpecialLocations.PatchByIdWithHttpMessagesAsync(id, locationType, "return=representation");
if (resp.Response.StatusCode == HttpStatusCode.BadRequest)
{
string jsonErrStr = await resp.Response.Content.ReadAsStringAsync();
JObject err = JObject.Parse(jsonErrStr);
string[] valPair = ((string)err["error"]["innererror"]["message"]).Split(":".ToCharArray());
//now push into MVC controller's modelstate, so jQuery validation can show it
this.ModelState.AddModelError(valPair[0].Trim(),valPair[1].Trim());
return View(locationType);
}
这篇关于我应该尝试使用从API返回的BadRequest(ModelState),并使用JSON.NET反序列化为* what *吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!