网页API - 如何直接从OnActionExecuting过滤器停止Web管道 [英] Web Api - how to stop the web pipeline directly from an OnActionExecuting Filter
本文介绍了网页API - 如何直接从OnActionExecuting过滤器停止Web管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个pre-动作的web API钩子,将检查ModelState.IsValid。如果ModelState中是无效的,我不想要执行的动作,只是立即返回我的消息。我这样做究竟怎么办?
公共类ValidateModelStateAttribute:ActionFilterAttribute
{
公共覆盖无效OnActionExecuting(System.Web.Http.Controllers.HttpActionContext ActionContext中){
如果(!actionContext.ModelState.IsValid)
{
VAR味精= actionContext.Request.CreateErrorResponse(的HTTPStatus code.BadRequest,actionContext.ModelState);
// 怎么办?
}
base.OnActionExecuting(ActionContext中);
}
}
解决方案
设置Response.Result。如果结果不为空,将不会执行该操作。确切的语法逃避我的权利,但它是为
一样简单 如果(actionContext.ModelState.IsValid == FALSE)
{
VAR响应= actionContext.Request.CreateErrorResponse(...);
actionContext.Response =响应;
}
I have a pre-action web api hook that will check ModelState.IsValid. If the ModelState is not valid I do not want to execute the action and just return my message immediately. How exactly do I do this?
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);
}
}
解决方案
set the Response.Result. If the result is not null it will not execute the action. the exact syntax is escaping me right now, but it's as simple as
if(actionContext.ModelState.IsValid == false)
{
var response = actionContext.Request.CreateErrorResponse(...);
actionContext.Response = response;
}
这篇关于网页API - 如何直接从OnActionExecuting过滤器停止Web管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文