为什么MessageHandler在MVC请求中执行?

时间:2015-03-11 08:36:57

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

我有一个项目包括MVC和Web API控制器。我有,

 GlobalConfiguration.MessageHandlers.Insert(0, new MessageHandler1());

但是当我请求一个MVC控制器时,它会执行这个处理程序。它伤害了我,因为SuppressDefaultHostAuthentication正在MVC请求上执行PassiveAuthenticationMessageHandler处理程序。我在MessageHandler1.SendAsync上放了一个断点,发现System.Web.HttpContext.Current.Handler = {System.Web.Mvc.MvcHandler}确认它是MVC请求。

栈跟踪,

MyApp.dll!MyApp.MessageHandler1.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Line 120    C#
    System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)   Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.Tracers.MessageHandlerTracer.AnonymousMethod__FabricatedMethod5()   Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.Tracers.MessageHandlerTracer.SendAsync.AnonymousMethod__0() Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<System.Net.Http.HttpResponseMessage>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace)    Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.Tracers.MessageHandlerTracer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)    Unknown
    System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)   Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.AnonymousMethod__FabricatedMethod6()    Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync.AnonymousMethod__1()  Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<System.Net.Http.HttpResponseMessage>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace)    Unknown
    System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
    System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)   Unknown
    System.Web.Http.dll!System.Web.Http.HttpServer.AnonymousMethod__FabricatedMethod9() Unknown
    System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync()  Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.HttpServer.SendAsync>(ref System.Web.Http.HttpServer.SendAsync stateMachine)  Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.HttpServer.SendAsync>(ref System.Web.Http.HttpServer.SendAsync stateMachine)  Unknown
    System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)  Unknown
    System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)  Unknown
    System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore()    Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore>(ref System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore stateMachine)    Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore>(ref System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore stateMachine)    Unknown
    System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore(Microsoft.Owin.IOwinContext context, Microsoft.Owin.IOwinRequest owinRequest, Microsoft.Owin.IOwinResponse owinResponse) Unknown
    System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.Invoke(Microsoft.Owin.IOwinContext context) Unknown
    Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke()  Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke stateMachine)  Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Threading.Tasks.VoidTaskResult>.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke stateMachine)   Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke stateMachine)  Unknown
    Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke(Microsoft.Owin.IOwinContext context)   Unknown
    Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke()    Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke stateMachine)  Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Threading.Tasks.VoidTaskResult>.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke stateMachine)   Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke stateMachine)  Unknown
    Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke(Microsoft.Owin.IOwinContext context) Unknown
    Microsoft.Owin.dll!Microsoft.Owin.Infrastructure.OwinMiddlewareTransition.Invoke(System.Collections.Generic.IDictionary<string,object> environment) Unknown
    Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.BeginEvent(object sender, System.EventArgs e, System.AsyncCallback cb, object extradata)  Unknown
    System.Web.dll!System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()   Unknown
    System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously)  Unknown
    System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error)   Unknown
    System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb)  Unknown
    System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context)    Unknown
    System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
    System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)   Unknown
    [Native to Managed Transition]  
    [Managed to Native Transition]  
    System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
    System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)   Unknown
    [AppDomain Transition]  

1 个答案:

答案 0 :(得分:0)

我只是使用自定义MessageHandler修复它,

GlobalConfiguration.SuppressDefaultHostAuthentication();
GlobalConfiguration.Filters.Add(new HostAuthenticationFilter(OAuthOptions.AuthenticationType));
GlobalConfiguration.MessageHandlers.Insert(0, new ResetMvcPrincipalMessageHandler());

    public class ResetMvcPrincipalMessageHandler : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var url = request.RequestUri.AbsolutePath;
            if (!url.Contains("/api/"))// not web api request
            {
                var principal = request.GetRequestContext().Principal;
                var response = await base.SendAsync(request, cancellationToken);;
                request.GetRequestContext().Principal = principal;
                return response;
            }
            return await base.SendAsync(request, cancellationToken);
        }
    }