簡體   English   中英

ASP.Net WebAPI從MediaTypeFormatter內部獲取當前控制器名稱

[英]ASP.Net WebAPI Get current controller name from inside MediaTypeFormatter

我正在編寫用於HTML的媒體類型格式化程序,以根據用戶的html請求自動生成Razor視圖。 我這樣做是為了在SelfHosted服務中使用。 我需要檢測請求了什么控制器/動作,以允許我選擇要渲染的視圖。

 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>

即返回,而不是MyCustomObjectMetadata<MyCustomObject> 作為元數據屬性,您可以設置控制器名稱和操作。 然后在格式化程序中,只需解耦元數據和您的自定義對象,然后僅序列化該自定義對象。

我在這里寫了有關此方法的博客-http: //www.strathweb.com/2012/06/extending-your-asp-net-web-api-responses-with-useful-metadata/ 盡管本文的目的有所不同,但是我相信您可以將其與您的需求聯系起來。

編輯 :或者如果您可以接受一些小技巧,請使用自定義過濾器和標題:

  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); } 

然后只需從格式化程序的標頭中讀取它,然后刪除標頭條目,這樣就不會將其發送到客戶端。

Web API Contrib在此處具有有效的RazorViewFormatter。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM