我们有不同的客户,每个客户都拥有一个数据库。
客户端使用HttpHeader DatabaseOwner发送请求:Samsung
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("DatabaseOwner", "Samsung");
在我的ApiController中,我希望我的Context基于该值并连接到正确的数据库
public class AuthController : ApiController
{
public CmpContext db { get; set; }
public AuthController(): base()
{
db = new CmpContext(VcsCmpConnectionstring.GetCMPConnectionString(this.Request));
}
// GET api/Auth
public IQueryable<DealerModel> GetDealer()
{
return db.Dealer;
}
public static string GetCMPConnectionString(HttpRequestMessage request)
{
string returnvalue;
if (request.Headers.Contains("DatabaseOwner"))
{
SqlConnectionStringBuilder ConnStringBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["CMPContext"].ConnectionString);
ConnStringBuilder.InitialCatalog = "vcs_cmp_" + request.Headers.GetValues("DatabaseOwner").First();
returnvalue = ConnStringBuilder.ToString();
}
else
{
throw new MissingFieldException("Header DatabaseOwneris null");
}
return returnvalue;
}
当我尝试获取此请求时,它始终为空
什么时候可以访问请求,还是有更好的方法在数据库之间切换?
巴伐利亚州的问候 帕特里克
答案 0 :(得分:1)
请求对象仅在调用APIController的Initialize函数后初始化。因此,在调用base.initialize之前,您无法访问Request。试着这样做:
public class AuthController : ApiController
{
protected override void Initialize(
System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
db = new CmpContext(
VcsCmpConnectionstring.GetCMPConnectionString(this.Request));
}
}