2015-04-01 60 views
3

我試圖從我編寫的自定義AuthorizationFilterAttributeOnAuthorization()方法中訪問第一個配置的媒體類型格式化程序。但是,當我訪問配置的「Formatters」屬性時,我得到MissingMethodException當從AuthorizationFilterAttribute訪問全局媒體類型格式化程序時發生MissingMethodException

不起作用:

public override void OnAuthorization(HttpActionContext actionContext) 
{ 
    // Perform authentication. 
    if (authenticationFailed) 
     actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) 
     { 
      Content = new ObjectContent<MyReturnType>(new MyReturnType(), actionContext.ControllerContext.Configuration.Formatters.First()) 
     }; 
} 

拋出system.missingMethodException而 - 未找到方法: 'System.Net.Http.Formatting.MediaTypeFormatterCollection System.Web.Http.HttpConfiguration.get_Formatters()'。

作品:

public override void OnAuthorization(HttpActionContext actionContext) 
{ 
    // Perform authentication. 
    if (authenticationFailed) 
     actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) 
     { 
      Content = new ObjectContent<MyReturnType>(new MyReturnType(), new JsonMediaTypeFormatter()) 
     }; 
} 

然而,因爲這個屬性是在正跨多個項目使用的庫定義,一些項目使用XML而不是JSON爲他們的「默認」的介質類型轉換器,我不能使用第二種方法,因爲我不知道以什麼格式返回數據。

替換actionContext.ControllerContext.Configuration.Formatters.First()GlobalConfiguration.Configuration.Formatters.First()也會導致例外。

我正在使用這種訪​​問「默認」媒體類型格式化程序的自定義ActionFilterAttribute沒有任何問題的相同方法,爲什麼這不會在AuthorizationFilterAttribute

有誰知道如何從AuthorizationFilterAttribute訪問已配置的介質類型格式化程序?

注:我意識到我可以有一種方式來指定媒體類型格式化程序作爲屬性初始化的一部分,但我希望我不必這樣做,我可以只是簡單地訪問配置媒體類型格式化程序。這和我很好奇,爲什麼這不起作用。

注2:正在使用的System.Web.Http DLL的版本是4.0。

回答

5

想通了,原來有一個程序集綁定在配置文件丟失:

<runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <dependentAssembly> 
      <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" /> 
      <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
      <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> 
      <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> 
     </dependentAssembly> 
    </assemblyBinding> 
</runtime> 
+0

真棒。謝謝! – Marcus 2015-11-19 12:06:07