从AuthorizationFilterAttribute访问全局媒体类型格式化程序时出现MissingMethodException

Ton*_*ony 4 c#-4.0 asp.net-web-api2

我试图从我正在编写OnAuthorization()的自定义方法中访问第一个配置的媒体类型格式化程序AuthorizationFilterAttribute.但是,当我访问配置的"Formatters"属性时,我得到了一个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())
        };
}
Run Code Online (Sandbox Code Playgroud)

throws 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())
        };
}
Run Code Online (Sandbox Code Playgroud)

但是,因为这个属性是在一个正在多个项目中使用的库中定义的,并且一些项目使用XML而不是JSON作为他们的"默认"媒体类型转换器,所以我不能使用第二种方法,因为我不喜欢不知道返回数据的格式.

更换actionContext.ControllerContext.Configuration.Formatters.First()GlobalConfiguration.Configuration.Formatters.First()也导致异常.

我使用相同的方法在自定义中访问"默认"媒体类型格式化程序ActionFilterAttribute没有任何问题,为什么这也不会在一个AuthorizationFilterAttribute

有谁知道如何从AuthorizationFilterAttribute?访问配置的媒体类型格式化程序?

注意:我意识到我可以指定媒体类型格式化程序作为属性初始化的一部分,但我希望我不必这样做,我只需访问配置的媒体类型格式化程序.那和我很好奇为什么这不起作用.

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

Ton*_*ony 7

弄清楚,原来在配置文件中缺少一个程序集绑定:

<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>
Run Code Online (Sandbox Code Playgroud)