我如何验证OnActionExecuting方法

时间:2019-02-05 13:38:11

标签: c# asp.net-mvc asp.net-web-api

当我的 OnActionExecuting 返回 True 时,我该如何交叉检查它是否允许我执行控制器方法,否则将其拒绝?

public class SessionExpireAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpContext ctx = HttpContext.Current;
            if (2 ==2)
            {
               // throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK));
                return (new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)));
            }
            else
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                return;
            }
            base.OnActionExecuting(actionContext);
        }

1 个答案:

答案 0 :(得分:0)

我认为您只需要在离开处理程序之前设置actionContext.Result属性即可。像这样:

public class SessionExpireAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        // Adjust this if statement so it's executed hit if your special authentication has *failed*
        if (true)
        {
            actionContext.Result = new HttpUnauthorizedResult("You don't have access to this resource.");
        }

        base.OnActionExecuting(actionContext);
    }
}

如果您未在处理程序中执行任何操作,则控制器操作将照常执行。