我在跟踪
this tutorial
尝试获取此图像中MessageHandler3的行为:
这是我的一个控制器的一部分:
public class UserController : ApiController
{
[Route("api/users")]
[ResponseType(typeof(User))]
public IHttpActionResult PostUser([FromBody]User newUser)
{
try
{
userService.InsertUser(newUser);
return Ok(newUser);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
}
这是处理程序的虚拟版本:
public class UserTokenHandler : DelegatingHandler
{
public UserTokenHandler()
{
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (true)//actual validation method
{
var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
下面是我对WebApiConfig类所做的更改:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//config.MapHttpAttributeRoutes();
var handlers = new DelegatingHandler[] { new UserTokenHandler() };
var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: routeHandlers
);
config.MapHttpAttributeRoutes();
}
}
我的问题是注释行。如果我不包含它或将它放在末尾(就像现在一样),处理程序就会执行,但当我尝试使用api时会出现以下错误:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:12986/api/users'.",
"MessageDetail": "No type was found that matches the controller named 'users'."
}
但是如果我取消注释它(并删除底部的一个),我将直接进入控制器,而不经过处理程序。
我希望它通过处理程序,然后找到方法,如何修复它?