Search code examples
c#asp.net-web-apimediatypeformatter

ASP.Net WebAPI Get current controller name from inside MediaTypeFormatter


I am writing a media type formatter for HTML to automatically generate a Razor view based on an html request from the user. I am doing this for use inside a SelfHosted service. I need to detect what controller/action was requested to allow me to pick the view to render into.

 public class RazorHtmlMediaTypeFormatter : MediaTypeFormatter
    {
        public RazorHtmlMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }

        public override bool CanWriteType(Type type)
        {
            return true;
        }

        public override bool CanReadType(Type type)
        {
            return false;
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, System.Net.TransportContext transportContext)
        {
            return Task.Factory.StartNew(() =>
                {
                    var view = Razor.Resolve(String.Format("{0}.{1}.cshtml", something.Controller, something.Action), value);

                    byte[] buf = System.Text.Encoding.Default.GetBytes(view.Run(new ExecuteContext()));
                    stream.Write(buf, 0, buf.Length);
                    stream.Flush();
                });
        }
    }

Solution

  • Web API Contrib has a working RazorViewFormatter in here.