我正在尝试根据请求的URL输出不同类型的格式。直到Preview5我做了以下操作来获取MediaTypeFormatters OnWriteToStream中的URI - 方法:
var requestUri = OperationContext.Current
.IncomingMessageHeaders
.To;
但是使用Preview6,OperationContext.Current属性始终为null。可能是因为格式化程序在不同的线程上执行。那么在MediaTypeFormatter中获取URI的正确方法是什么?或者是否有一个替代MediaTypeFormatter的请求作为参数?
提前谢谢。
此致
...
勒夫
答案 0 :(得分:0)
您可以使用显示为here的UriFormatExtensionMessageChannel / OperationHandler。
答案 1 :(得分:0)
为了完整起见,我决定使用以下解决方案
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;
}
...
}
答案 2 :(得分:0)
对于我们的Web API,我们也遇到了MediaTypeFormatter
这个问题,但我们只是使用HttpContext.Current.Request.Url
而不是通过OperationContext.Current
解决了这个问题。