gpt4 book ai didi

c#-4.0 - 从 AuthorizationFilterAttribute 访问全局媒体类型格式化程序时 MissingMethodException

转载 作者:行者123 更新时间:2023-12-02 22:13:05 25 4
gpt4 key购买 nike

我正在尝试从我正在编写的自定义AuthorizationFilterAttributeOnAuthorization() 方法中访问第一个配置的媒体类型格式化程序。但是,当我访问配置的“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())
};
}

抛出 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。

最佳答案

发现了,配置文件中缺少程序集绑定(bind):

<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>

关于c#-4.0 - 从 AuthorizationFilterAttribute 访问全局媒体类型格式化程序时 MissingMethodException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com