Dan*_*bdn 8 c# validation json asp.net-web-api angularjs
我正在创建一个AngularJS Web表单,使用WebAPI设置作为OData对表执行POST(插入).我试图返回一个失败的验证ModelState对象(以JSON格式)以验证表单上的相应字段.
我得到的所有内容都是一个字符串,所有细节都以字符串形式显示(不是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":""
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的post方法如下所示:
public async Task<IHttpActionResult> Post(Application application)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Applications.Add(application);
await db.SaveChangesAsync();
return Created(application);
}
Run Code Online (Sandbox Code Playgroud)
我甚至尝试将其抽象为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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的WebApi start方法具有以下配置:
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();
Run Code Online (Sandbox Code Playgroud)
这是我想要实现的(与我上面的例子不匹配):
{
"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."
]
}
}
Run Code Online (Sandbox Code Playgroud)
我需要返回ModelState,以便在相应的字段中定位验证反馈.
我可以检查/改变什么想法让它按照需要工作?
谢谢.
更新1 - 在asp.net上找到的参考
OData错误响应不包含模型状态错误
使用CreateErrorResponse扩展方法或HttpErrors直接创建错误响应时,错误将映射到OData错误响应.错误响应中的任何模型状态错误都不会传播到OData错误响应.要保留OData错误响应中的模型状态错误,请直接使用CreateODataErrorResponse扩展方法或ODataError,并将模型状态错误的描述添加到OData错误消息中.
小智 0
OData 用作ODataError
错误响应。ODataError
和 之间的区别HttpEror
在于 HttpError 派生自Dictionary<string, object>
,因此当它实例化 时ModelStateDictionary
,所有模型错误都会设置为ModelState
属性。但是,当您请求 OData 时,HttpError
对象会映射到属性ODataError
,并且所有验证错误都会连接到InnterError
属性中。
归档时间: |
|
查看次数: |
1729 次 |
最近记录: |