自定义主体被覆盖

时间:2014-05-29 15:00:35

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

我的自定义主体在执行控制器操作之前被覆盖但我不知道在哪里。我像这样设置校长:

public class CustomMessageHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        IPrincipal principal = new CustomPrincipal(Thread.CurrentPrincipal);
        Thread.CurrentPrincipal = principal;
        if(HttpContext.Current != null)
            HttpContext.Current.User = principal;
        request.GetRequestContext().Principal = principal;
        var response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}

如您所见,我尝试了几种设置主体的方法。但是,当方法SendAsync执行时,将覆盖principal。我在该行之前和我的action方法中检查了当前的线程ID。 ID是相同的。如何以正确的方式设置委托人?

注意:它托管在IIS

1 个答案:

答案 0 :(得分:1)

我找到了它。在WebApiConfig课程中,会自动添加一个过滤器。

config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

我反编译HostAuthenticationFilter并且有一个方法可以覆盖它。反编译代码:

public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    }
    HttpRequestMessage request = context.Request;
    if (request == null)
    {
        throw new InvalidOperationException(OwinResources.HttpAuthenticationContext_RequestMustNotBeNull);
    }
    IAuthenticationManager authenticationManagerOrThrow = GetAuthenticationManagerOrThrow(request);
    cancellationToken.ThrowIfCancellationRequested();
    AuthenticateResult asyncVariable0 = await authenticationManagerOrThrow.AuthenticateAsync(this._authenticationType);
    if (asyncVariable0 != null)
    {
        IIdentity identity = asyncVariable0.Identity;
        if (identity != null)
        {
            context.Principal = new ClaimsPrincipal(identity);
        }
    }
}

所以我对过滤器进行了评论并且有效:)