Return postsharp OnMethodBoundaryAspect 的未经授权的结果

Return Unauthorized result with postsharp OnMethodBoundaryAspect

我有一些 api 操作,我在 OnMethodBoundaryAspect 中包含了一个方面, 我对请求中发送的令牌进行验证,就像这样。

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Instance)]
public class TokenCallHandler : OnMethodBoundaryAspect
{
    /// <summary>
    /// Methodo responsável por validar o token enviado pelo usuário
    /// </summary>
    /// <param name="args"></param>
    public override void OnEntry(MethodExecutionArgs args)
    {
        ApiController apiController = (ApiController)args.Instance;
        var context = apiController.ControllerContext;
        HttpRequestHeaders headers = context.Request.Headers;
        bool validToken = false;
        if (headers.Contains("X-Authorization"))
        {
            var authorization = headers.GetValues("X-Authorization");
            var token = authorization.ToList().FirstOrDefault();
            if (token == null)
                token = "invalid";

            validToken = TokenUtil.ValidateToken(token);

        }

        if (!validToken)
            args.ReturnValue = new UnauthorizedAccessException();



    }

}

但是一直执行api里面的方法,我只想return401异常

如果我确实抛出新的 UnauthorizedException,它 return 带有 500(内部服务器错误),其中未经授权,但我需要 401。

如何在 wep.api 动作中捕捉 returned 方面?

所述

You should be throwing a HttpResponseException from your API method

通过设置 args.ReturnValue,您正在更改由您的方面增强的方法的 return 值,但您应该抛出异常。

所以最后一行应该是

throw new HttpResponseException(HttpStatusCode.Unauthorized);

Or, if you want to supply a custom message:

var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" }; throw new HttpResponseException(msg);

您也可以考虑使用 MethodInterceptionAspect (http://doc.postsharp.net/method-interception),因为您没有包装方法执行,而是拦截它。