Jon Hoguet
Jon Hoguet

Reputation: 93

How to get HttpRequestMessage instead of HttpContext.Current in WebApi

I have found several sources that say that you should not use HttpContext.Current in WebApi but none that say how you should handle those cases where we used to use HttpContext.Current.

For example, I have a LinkProvider class that creates links for an object. (simplified to stay on topic).

public abstract class LinkProvider<T> : ILinkProvider<T>
{
  protected ILink CreateLink(string linkRelation, string routeName, RouteValueDictionary routeValues)
  {
    var context = System.Web.HttpContext.Current.Request.RequestContext;

    var urlHelper = new System.Web.Mvc.UrlHelper(context);
    var url = string.Format("{0}{1}", context.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority), urlHelper.RouteUrl(routeName, routeValues));

    ///...

    return new Link(linkRelation, url);
  }
}

and this class is used by a MediaTypeFormatter.

This class is expected to build a link using the same host that came from the original request and leveraging any route values that were on the original request.

But... how do I get a hold of the HttpRequestMessage? This will be encapsulated by a MediaTypeFormatter - but it doesn't have one either.

There must be an easy way to get hold of the HttpRequestMessage - what am I overlooking?

thanks

Jon

Upvotes: 5

Views: 5782

Answers (1)

Jon Hoguet
Jon Hoguet

Reputation: 93

I ended up creating the following base Formatter which exposes the request, now I will be able to pass it along to the LinkProvider.

public class JsonMediaTypeFormatterBase : JsonMediaTypeFormatter
{

  public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, MediaTypeHeaderValue mediaType)
  {
    Request = request;
    return base.GetPerRequestFormatterInstance(type, request, mediaType);
  }

  protected HttpRequestMessage Request
  {
    get;
    set;
  }
}

Upvotes: 2

Related Questions