我正在创建一个AngularJS Web窗体,以使用WebAPI设置作为OData执行POST(插入)到表中。我试图找回失败的验证ModelState对象(以JSON格式)以验证表单上的相应字段。WebAPI OData未通过验证ModelState对象未返回
所有我回来是一个字符串的所有细节作为一个字符串(不以JSON解析的格式)
{
"odata.error":{
"code":"","message":{
"lang":"en-US","value":"The request is invalid."
},"innererror":{
"message":"application.ApplicationName : The ApplicationName field is required.\r\n","type":"","stacktrace":""
}
}
}
我交的方法是这样的:
public async Task<IHttpActionResult> Post(Application application)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Applications.Add(application);
await db.SaveChangesAsync();
return Created(application);
}
我甚至试图将其抽象为ActionFilterAttribute,但结果仍然相同
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
我的WebApi启动方法有以下配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Application>("DataApplications");
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include };
Configure(config);
config.EnableQuerySupport();
// Use camel case for JSON data.
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
这就是我想要的实现(不匹配我上面的例子):
{
"Message": "The request is invalid.",
"ModelState": {
"car": [
"Required property 'Make' not found in JSON. Path '', line 1, position 57."
],
"car.Make" : [
"The Make field is required."
],
"car.Price": [
"The field Price must be between 0 and 200000."
]
}
}
我需要的ModelState回来,我可以指定在验证反馈适当的领域。
任何想法我可以检查/更改以使其按照需要工作?
谢谢。
更新1 - 参考上asp.net发现
OData的错误响应不包含模型状态误差
当使用CreateErrorResponse扩展方法或创建一个错误响应HttpErrors直接该错误被映射到OData错误响应。错误响应中的任何模型状态错误都不会传播到OData错误响应。为了保持在OData的错误响应的模型状态误差直接使用CreateODataErrorResponse扩展方法或ODataError并添加模型状态误差的描述到的OData错误消息。
你找到一个解决办法? – iuristona