Webapi 2自定义授权不执行方法

时间:2018-06-07 21:48:47

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

我创建了一个自定义授权类来验证用户令牌。这是web api 2.

问题是,自定义授权验证令牌,但之后不执行控制器中的方法。验证令牌后,它应该在控制器中执行用户方法。我已经调试了代码,我可以看到授权令牌得到了正确验证,但没有执行该方法,只返回200.

有人可以帮忙吗? (我是新来的)

自定义授权类代码:

public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);


            if (actionContext.Request.Headers.Authorization.Parameter != null)
            {
                string authenticationToken = Convert.ToString(actionContext.Request.Headers.Authorization.Parameter);
                PartnerUserProfile user = new PartnerUserProfile();
                user = user.validate_token(authenticationToken);

                if (user.recordref > 0) //above user has some content and matches the token from validate_token method. it wil be blank if not
                {


                    return;

                }
                else
                {
                    HttpContext.Current.Response.AddHeader("Bearer", authenticationToken);
                    HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
                    return;
                }
            }

            actionContext.Response =  actionContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
            actionContext.Response.ReasonPhrase = "Please provide valid inputs";
            return;

        }

    }

我的控制器低于此值永远不会被执行。

   [HttpPost]
    [CustomAuthorize]
    public IHttpActionResult user(PartnerUserProfile user) //setUser
    {
        ReturnData rd = user.setPartnerUserProfile();
        if (rd.status == 0)
        {
            return BadRequest("Invalid");
        }
        return Ok(rd);
    }

1 个答案:

答案 0 :(得分:1)

当您为Response分配值时,它会短路并立即返回。只有在没有短路时才会执行控制器逻辑(在Filter中设置了响应)。

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#cancellation-and-short-circuiting