调用来自其他路由的WebAPI路由消息处理程序

时间:2013-07-26 11:03:43

标签: asp.net-web-api asp.net-web-api-routing owin katana

我目前正在使用在OWIN / Katana上运行的WebAPI。我已经定义了两个消息处理程序:

  • CorsHandler:允许CORS(跨域资源共享),将应用于所有HTTP消息
  • HmacAuthenticationHandler:检查用户是否经过身份验证,只会应用于需要身份验证的路由。

我的HttpConfiguration将配置如下:

var config = new HttpConfiguration();

/* configure routes for the web API */
// ### public routes ###
config.Routes.MapHttpRoute("IndexRoute", "", new {controller = "Main", action = "get"});
config.Routes.MapHttpRoute("LoginRoute", "login", new {controller = "Account", action = "Login"});
config.Routes.MapHttpRoute("RegisterRoute", "register", new {controller = "Account", action = "Register"});

// ### routes that need authentication ###
// according to http://www.asp.net/web-api/overview/working-with-http/http-message-handlers  (last example)

// List of delegating handlers.
var handlers = new DelegatingHandler[] {
  new HmacAuthenticationHandler(controllerConfig.StorageHelper.UserLoginInfo)
};
// Create a message handler chain with an end-point.
var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers);

// configure route
config.Routes.MapHttpRoute("DefaultRoute",
  "{controller}/{id}",
  new {id = RouteParameter.Optional},
  null,
  routeHandlers);

/* other settings (JSON formatting, ...) */

/* dependency resolver, which will pass an instance of my DAO factory to each controller */
config.DependencyResolver = new ControllerDependencyResolver(daoFactory);

/* apply CORS message handler to all messges */
config.MessageHandlers.Add(new CorsHandler());

如果我通过AJAX调用调用Web API方法,需要身份验证(例如“127.0.0.1:80/test/id”),一切都按预期工作。将调用消息处理程序,如下所示:

有效用户凭据:

客户 - > CorsHandler - > HmacAuthenticationHandler - > TestController(get(id)) - > CorsHandler - > HmacAuthenticationHandler - >客户(OK-200)

无效用户凭据:

客户 - > CorsHandler - > HmacAuthenticationHandler - > CorsHandler - > HmacAuthenticationHandler - >客户(未经授权的请求-403)


但是如果我通过AJAX调用调用Web API方法,不需要身份验证(例如“127.0.0.1:80/login”)。 HmacAuthenticationHandler将在“返回客户端的路上”被调用,即使它未分配给此路由:

客户 - > CorsHandler - > AccountController(登录) - > CorsHandler - > HmacAuthenticationHandler - >客户(OK-200)

为什么要在“公共路线”上调用HmacAuthenticationHandler(在回复期间)?奇怪的是它不会影响响应,客户端仍然可以获得OK-200。


更新

我已经创建了一个示例项目并用假的替换了所有内部接口/实现,可以在BitBucket上找到并下载代码:

https://bitbucket.org/Robar/stackoverflowquestionwebapi

0 个答案:

没有答案