2

So, I am trying to build my first web api using MVC 4. All is going well. I managed to get basic authentication working with my site (using SSL) but I have a problem, sort of.

I have this tiny bit of code on every ApiController:

    private Profile user
    {
        get
        {                
            var UserId = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();
            var Profile = new Profile(UserId);
            return Profile;
        }
    }

I do this, because my custom Profile has some extra fields in it; namely the CompanyId. All of my functions require this CompanyId to get data. I was thinking of using the CompanyId as a token, but I couldn't get that to work :D

So my question is: Is there a way of globally storing the CompanyId for each request? Perhaps in a filter to a route Message Handler. I know I can't use sessions, etc, because the API is stateless but on the other hand I don't want to have repetitive code all the time....

2 Answers 2

1

You have two options:

  1. (the simpler one) Use one of the page processing events (in Global.asax) to fetch the profile information and store it in HttpContext
  2. Create your own HttpModule which will do the same (fetch the profile and store it in HttpContext)

You can than access HttpContext from API methods. I would go with the first option because it is much simpler.

Sign up to request clarification or add additional context in comments.

Comments

1

Other than the options mentioned by @Alon, I highly recommend you to look at Dependency Injection(DI) and DI containers such as Autofac. Using DI you can push the dependencies like in this case Profile into API controller or as a matter of fact into any class that require Profile.

Since constructor injection is a preferred mechanism here is how the class signature becomes

public class Class1 {
    public Profile CurrentUserProfile { get;private set;}

    public Class1(Profile profile){
       this.CurrentUserProfile=profile;   // Now you can use it throughout the class.
    }
}

You can inject such dependencies into base class, like a BaseApiController.

The Autofac registration then would look like

builder.Register<Gateway.IRequestContextBuilder>((c) =>
{
            var UserId = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();
            var Profile = new Profile(UserId);
            return Profile;

}).InstancePerHttpRequest();

This would create the Profile object once per HTTP request and then it can be injected into any dependent class.

This may seem confusing to you, but once you understand the DI concepts and containers like Autofac, this would start to make more sense.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.