Reputation: 2115
I Have a MVC 5 application whose back-end is web API. For each request to my server I need to provide user-agent which I can get in controller action method like var UserAgent = Request.UserAgent.ToString();
and pass subsequently in other class like (Controller => Service => HttpRequester => XXXHttpClient) and finally use in actual request in XXXHttpClient class but I think there could be a better way to achieve the same. I tried to google it but didn't find anything relevant so can anyone guide me what would be the best practice If I want to get user-agent directly in XXXHttpClient class instead of passing subsequently.
Upvotes: 0
Views: 9758
Reputation: 58743
Little bit of a broad question with a lot of possible answers.
Passing the data through all the layers is usually not a good thing.
What I would do is make an MVC action filter that grabs the user agent and sets it to an object. The object class could be like this:
public class RequestContext
{
public string UserAgent { get; set; }
}
Use your dependency injection framework to inject this once-per-request. Then the action filter and the layer that depends on the data would use the same instance, allowing you to get the data to any layer that needs it.
Another option which uses a static property:
HttpContext.Current.Request.UserAgent
Greater performance, easier to read, but lower testability :)
Upvotes: 6