1

I am using web api project with Entity framework and i was planning to make the Entity Framework as dynamic one [ change the connection string at run time]

In a normal MVC application i did this like

public class ApiRepository
{
    public WebApiLabDbEntities dbContext; 
    public ApiRepository()
    {
        string connection_string = (string)(System.Web.HttpContext.Current.Session["Connection"]);
        if (String.IsNullOrEmpty(connection_string))
        {
            dbContext = new WebApiLabDbEntities();
        }
        else
        {
            dbContext = new WebApiLabDbEntities(connection_string);
        }


    }

}

But in a webapi project i cant set the connection string in a session object like Session["Connection"]

So what is the alternative way to achieve the same? The web api is going to use token based authentication and the auth_token decides the connection string to be used.

Sebastian
  • 4,625
  • 17
  • 76
  • 145
  • It sounds like what you want is to use Session in WebAPI. This is possible. Take this as example http://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api – smoksnes Apr 26 '16 at 06:36
  • I was planning to read access_token and based on it construct connection_string and keep it in some place like either session or append to request [ dont know is possible or not ] and then access from either Session or from Request object – Sebastian Apr 26 '16 at 06:48

1 Answers1

0

If your connection string depends on the authenticated user, then you should apply your logic based on current user Claims (e.g. using Thread.CurrentPrincipal as ClaimsPrincipal and reading issued claims).

Of course this means that you should issue a claim that will make your Identity aware of the different connection strings.

This is a board topic and strongly depends on what kind of authentication, authorization and identity framework you are using behind the scenes, but this post could lead you towards the right direction: ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5

Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56