asp.net - Web Api - 如何直接从 OnActionExecuting 过滤器停止 Web 管道

标签 asp.net asp.net-web-api action-filter

我有一个 pre-action web api hook 将检查 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);
    }
}

最佳答案

设置 Response.Result。如果结果不为空,则不会执行该操作。确切的语法现在正在逃避我,但它就像

if(actionContext.ModelState.IsValid == false)
{
       var response = actionContext.Request.CreateErrorResponse(...);
       actionContext.Response = response;
}   

关于asp.net - Web Api - 如何直接从 OnActionExecuting 过滤器停止 Web 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822365/

相关文章:

c# - 在 ASP .Net Core 中的 ExceptionFilterAttribute 中添加响应 header

javascript - 通缉 : jQuery selector with variable part in the middle

c# - 如何从无序列表项调用代码隐藏代码

asp.net - 有没有办法使用 Web api 从一篇笔记中提取部分和笔记

c# - 对象引用未设置为对象的实例......但它是?

c# - 无法解析从外部 dll 加载的 Controller

c# - Angularjs 和 WebAPI Put 方法参数始终为空

asp.net-web-api - asp.net web api 自托管/owin/katana

scala - 如何在 Play 2.1 中过滤访问代码请求

model-view-controller - 使用 Action 过滤器进行MVC错误处理