我正在創建一個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