Jean Libera
Jean Libera

Reputation: 629

In a WebAPI Formatter, how can you get the URL from HttpContent?

In a WebAPI service, we are using a Formatter to read a content parameter on a request. We need access to the URL in order to transform the content parameter correctly. HttpRequestMessage isn't available, and we can't use HttpContext.Current.Request because HttpContext.Current is null. Accessing the HttpRequestMessage on a Read was requested at http://aspnetwebstack.codeplex.com/workitem/82, but this issue was closed because HttpContent is available on a Read. However, I don't know how to get the URL from HttpContent, or even if it's possible.

Upvotes: 4

Views: 1641

Answers (1)

Kiran
Kiran

Reputation: 57989

There is a method called GetPerRequestFormatterInstance on the formatter which you can override to create a new instance of the formatter with the stateful information about the request in it. By the way, this method GetPerRequestFormatterInstance is only called during the request's deserialization stage. Example below:

public class TextPlainFormatter : BufferedMediaTypeFormatter
{
    public TextPlainFormatter()
    {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

    public HttpRequestMessage CurrentRequest
    {
        get;
        private set;
    }

    public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
    {
        TextPlainFormatter frmtr = new TextPlainFormatter();
        frmtr.CurrentRequest = request;

        //Copy from the original formatter instance to the new instance
        frmtr.MediaTypeMappings.Clear();
        foreach (MediaTypeMapping mediaTypeMapping in this.MediaTypeMappings)
        {
            frmtr.MediaTypeMappings.Add(mediaTypeMapping);
        }

        frmtr.RequiredMemberSelector = this.RequiredMemberSelector;

        frmtr.SupportedEncodings.Clear();
        foreach (Encoding supportedEncoding in this.SupportedEncodings)
        {
            frmtr.SupportedEncodings.Add(supportedEncoding);
        }

        frmtr.SupportedMediaTypes.Clear();
        foreach (MediaTypeHeaderValue supportedMediaType in this.SupportedMediaTypes)
        {
            frmtr.SupportedMediaTypes.Add(supportedMediaType);
        }

        return frmtr;
    }

Upvotes: 3

Related Questions