我正在为 HTML 编写媒体类型格式化程序,以根据用户的 html 请求自动生成 Razor View 。我这样做是为了在 SelfHosted 服务中使用。我需要检测请求了哪些 Controller /操作,以允许我选择要渲染到的 View 。
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();
});
}
}
请您参考如下方法:
为什么不将返回的对象包装在 Metadata<T> 中? ?
即返回,而不是 MyCustomObject , Metadata<MyCustomObject> .作为元数据属性,您可以设置 Controller 名称和操作。然后在格式化程序中,只需分离元数据和您的自定义对象,并仅序列化该自定义对象。
我在这里写了关于这种方法的博客 - http://www.strathweb.com/2012/06/extending-your-asp-net-web-api-responses-with-useful-metadata/ .虽然本文的目的有点不同,但我相信您可以将其与您的需求联系起来。
编辑:或者如果您对小技巧没意见,请使用自定义过滤器和 header :
public override void OnActionExecuting(HttpActionContext actionContext) { actionContext.Response.Headers.Add("controller", actionContext.ActionDescriptor.ControllerDescriptor.ControllerName); actionContext.Response.Headers.Add("action", actionContext.ActionDescriptor.ActionName;); base.OnActionExecuting(actionContext); }
然后只需从格式化程序的 header 中读取它,并删除 header 条目,这样它们就不会发送到客户端。
