对于基本身份验证,我已经实现了一个HttpMessageHandler基于Darin Dimitrov在这里回答的示例的自定义:https://stackoverflow.com/a/11536349/270591
代码创建具有用户名和角色principal的类型实例,GenericPrincipal然后将此主体设置为线程的当前主体:
Thread.CurrentPrincipal = principal;
Run Code Online (Sandbox Code Playgroud)
稍后在ApiController方法中,可以通过访问controllers User属性来读取主体:
public class ValuesController : ApiController
{
public void Post(TestModel model)
{
var user = User; // this should be the principal set in the handler
//...
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎工作正常,直到我最近添加了一个MediaTypeFormatter使用该Task库的自定义,如下所示:
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream,
HttpContent content, IFormatterLogger formatterLogger)
{
var task = Task.Factory.StartNew(() =>
{
// some formatting happens and finally a TestModel is …Run Code Online (Sandbox Code Playgroud) 我能够在global.asax.cs中为Web API路由ala成功注册一个自定义路由处理程序(从IRouteHandler派生):
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{client}/api/1.0/{controller}/{action}/{id}",
defaults: new{id = UrlParameter.Optional}
).RouteHandler = new SingleActionAPIRouteHandler();
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试为集成测试设置内存主机时,我似乎无法找到一种方法,当我调用HttpConfiguration.Routes.MapRoute时,我无法在返回的IHttpRoute上设置处理程序.
我应该采用不同的方式(例如使用自定义的HttpControllerSelector)吗?在两种情况下,我显然都喜欢这样做.
谢谢,马特
编辑:
所以我最终做的基本上是遵循下面的建议,但只是重写HttpControllerDispatcher类,如下所示:
public class CustomHttpControllerDispatcher : HttpControllerDispatcher
{
public CustomHttpControllerDispatcher(HttpConfiguration configuration) : base(configuration)
{
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// My stuff here
return base.SendAsync(request, cancellationToken);
}
}
Run Code Online (Sandbox Code Playgroud)