今天我在Web Api应用程序中遇到了一个奇怪的行为
protected void Application_Start() { FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); GlobalConfiguration.Configuration .MessageHandlers.Add(new DummyMessageHandler()); }
而我的DelegatingHandler看起来像这样.
public class DummyMessageHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request,CancellationToken cancellationToken) { * if (request.Headers.Authorization.Scheme == "Basic") Thread.CurrentPrincipal = new GenericPrincipal( new GenericIdentity("Authenticated"),new string[0]); return base.SendAsync(request,cancellationToken); } }
我遇到的问题是委托处理程序没有被执行.我在一个标有*的行中有一个断点,我的代码的执行永远不会停止.
我的nuget packages.config如下:
<?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net40" /> <package id="Microsoft.AspNet.Razor" version="2.0.20710.0" targetFramework="net40" /> <package id="Microsoft.AspNet.Web.Optimization" version="1.0.0" targetFramework="net40" /> <package id="Microsoft.AspNet.WebApi" version="4.0.20710.0" targetFramework="net40" /> <package id="Microsoft.AspNet.WebApi.Client" version="4.1.0-alpha-120809" targetFramework="net40" /> <package id="Microsoft.AspNet.WebApi.Core" version="4.0.20710.0" targetFramework="net40" /> <package id="Microsoft.AspNet.WebApi.WebHost" version="4.0.20710.0" targetFramework="net40" /> <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net40" /> <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net40" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net40" /> <package id="Newtonsoft.Json" version="4.5.8" targetFramework="net40" /> <package id="WebGrease" version="1.1.0" targetFramework="net40" /> </packages>
我在看这个很长一段时间,你能不能指出我失踪的东西?
谢谢
解决方法
你做的是正确的可能会发生此问题,因为DelegatingHandler仅在调用Web API Controller操作时运行.例如:
这将调用您的消息处理程序,因为它是一个ApiController.
public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1","value2" }; } }
这不会,因为它只是一个控制器.
public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } }
确保您正在调用Web API Controller操作,否则调试器不会打破您的断点.