是否可以在控制器构造函数中读取标题Authorization
?如何?这是实现我的目标的最佳解决方案(在控制器构造函数中读取标题值)吗?
以下是我的继承接口的类的代码:
public interface IProvider
{
string SendData(string data);
//other methods
}
public class FirstProvider : IProvider
{
private string _url;
public FirstProvider(string url)
{
_url = url;
}
public string SendData(string data)
{
//send data to First provider website (_url)
//return result
}
}
public class SecondProvider : IProvider
{
//some code
}
以下API控制器:
public class ProviderController : ApiController
{
private IProvider _provider;
public ProviderController()
{
//read authorization key from headers (How??)
string authToken;
//fetch from database/cache what provider to use based on the authorization key
var provider = Providers.GetProvider(authToken);
//Initialize _provider based on the database query result
if (provider.Name == "a")
{
_provider = new FirstProvider(provider.Data);
}
else if (provider.Name == "b")
{
_provider = new SecondProvider(provider.Data);
}
//Other providers will be added in future
}
public ProviderController(IProvider provider)
{
_provider = provider;
}
public IHttpActionResult SendData(string data)
{
_provider.SendData(data);
return Ok();
}
}
答案 0 :(得分:4)
您可以使用System.Web.HttpContext.Current.Request.Headers
但是,你应该使用构造函数注入(你似乎已经开始使用其他构造函数public ProviderController(IProvider provider)
您可以使用IOC容器根据请求执行条件绑定。看到 Ninject injection based on a route data value