rezord
rezord

Reputation: 53

How to access token's data in dbcontext

I have web api application .net framework 4.6.2 and we store user credentials in the token. I override dbcontext.savechanges to track database changes. I want to access userId which is stored in token and in api I can access that by httpContext. But the HTTP context is not available in dbcontext.

Upvotes: 0

Views: 767

Answers (2)

Alexandre Rodrigues
Alexandre Rodrigues

Reputation: 730

As @GPW said that's a poor design decision. To solve that situation you need to use IoC to do registrations such as:

// Autofac
builder.Register(c => new HttpContextWrapper(HttpContext.Current))
            .As<HttpContextBase>()
            .InstancePerRequest();

// Again Autofac 
builder.RegisterModule(new AutofacWebTypesModule());
// Castle Windsor
container.Register(Component.For<HttpContextBase()
                  .LifeStyle.PerWebRequest
                  .UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));

With controllers using contructor injection:

public class HomeController : Controller
{
    private readonly HttpContextBase _httpContext;

    public HomeController(HttpContextBase httpContext)
    {
        _httpContext = httpContext;
    }
}

So you inject HttpContextBase in order to access the context

public class EntitiesContext : DbContext
{

    private readonly HttpContextBase _httpContext;

    public EntitiesContext(HttpContextBase httpContext)
    {
        _httpContext = httpContext;
    }

}

Upvotes: 1

GPW
GPW

Reputation: 2626

Does System.Web.HttpContext.Current get the current Request Context?

I should point out that adding stuff that references this directly into a DbContext is poor design though... You should probably use Dependency Injection and manage this via some service with a lifetime scoped to the request - or at least that's how I'd do it...

Upvotes: 1

Related Questions