Geo*_*uer 16 asp.net action-filter asp.net-web-api
我有一个pre-action web api钩子,它将检查ModelState.IsValid.如果ModelState无效,我不想执行该操作,只是立即返回我的消息.我到底该怎么做?
public class ValidateModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) {
if (!actionContext.ModelState.IsValid)
{
var msg = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
// Now What?
}
base.OnActionExecuting(actionContext);
}
}
Run Code Online (Sandbox Code Playgroud)
Jas*_*ley 34
设置Response.Result.如果结果不为null,则不会执行该操作.确切的语法现在正在逃避我,但它很简单
if(actionContext.ModelState.IsValid == false)
{
var response = actionContext.Request.CreateErrorResponse(...);
actionContext.Response = response;
}
Run Code Online (Sandbox Code Playgroud)
您是否真的在ASP.NET WebApi页面上看到了这个示例?
看起来非常像你想要实现的,他们所做的就是设置Context对象的Response:
If model validation fails, this filter returns an HTTP response that contains the validation errors. In that case, the controller action is not invoked.
http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
看到: Handling Validation Errors
| 归档时间: |
|
| 查看次数: |
15315 次 |
| 最近记录: |