2

I'm trying to output different formats of a type depending on the URL of the request. Up to Preview5 I did the following to get the URI in the MediaTypeFormatters OnWriteToStream-Method:

var requestUri = OperationContext.Current
                                 .IncomingMessageHeaders
                                 .To;

But with Preview6 the OperationContext.Current property is always null. Probably because the formatter gets executed on a different thread. So what is the correct way to get the URI in the MediaTypeFormatter? Or is there an alternative to the MediaTypeFormatter which has the request as argument?

Thank you in advance.

Regards

...

Joachim

Joachim Rosskopf
  • 1,259
  • 2
  • 13
  • 24

3 Answers3

0

We also encountered this problem with a MediaTypeFormatter for our Web API but we solved it by simply using HttpContext.Current.Request.Url instead of going through OperationContext.Current.

Seph
  • 8,472
  • 10
  • 63
  • 94
0

You can use an UriFormatExtensionMessageChannel / OperationHandler as shown here.

Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124
0

For the sake of completeness I settled with the following solution

public class RazorHtmlHandler : HttpOperationHandler<HttpResponseMessage, HttpResponseMessage>
{
    public static readonly String OUTPUT_PARAMETER_NAME = "response";
    public static readonly MediaTypeWithQualityHeaderValue HTML_MEDIA_TYPE = new MediaTypeWithQualityHeaderValue("text/html");

    public const String DEFAULT_TEMPLATE_NAME = "index.cshtml";
    public const String DEFAULT_TEMPLATE_EXTENSION = ".cshtml";
    public const String DEFAULT_RAZOR_NAME = "_RazorHtmlProcessor_Template";

    public RazorHtmlHandler() : base(OUTPUT_PARAMETER_NAME)
    { }

    protected override HttpResponseMessage OnHandle(HttpResponseMessage response)
    {
        var request = response.RequestMessage;
        var accept = request.Headers.Accept;

        if (!accept.Contains(HTML_MEDIA_TYPE))
            return response;

        var buffer = new StringBuilder();
        var currentContent = response.Content as ObjectContent;

        try
        {                
            var template = LoadTemplateForResponse(request.RequestUri, currentContent);
            var value = ReadValueFormObjectContent(currentContent);

            buffer.Append(InvokeRazorParse(template, value));
        }
        catch (Exception ex)
        {
            throw new HttpResponseException(HttpStatusCode.InternalServerError);
        }

        response.Content = new StringContent(buffer.ToString(), 
                                             Encoding.UTF8, 
                                             HTML_MEDIA_TYPE.MediaType);
        return response;
    }
    ...
}
Joachim Rosskopf
  • 1,259
  • 2
  • 13
  • 24