I am trying to access the first configured media type formatter from within the OnAuthorization()
method of a custom AuthorizationFilterAttribute
that I am writing. However, when I access the "Formatters" property of the configuration, I am getting a MissingMethodException
.
Doesn't work:
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())
};
}
throws System.MissingMethodException - Method not found: 'System.Net.Http.Formatting.MediaTypeFormatterCollection System.Web.Http.HttpConfiguration.get_Formatters()'.
Works:
public override void OnAuthorization(HttpActionContext actionContext)
{
// Perform authentication.
if (authenticationFailed)
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new ObjectContent<MyReturnType>(new MyReturnType(), new JsonMediaTypeFormatter())
};
}
However, because this attribute is defined in a library that is being used across several projects, and some of the projects use XML instead of JSON for their "default" media type converter, I can't use the second approach that works since I don't know what format to return the data in.
Replacing actionContext.ControllerContext.Configuration.Formatters.First()
with GlobalConfiguration.Configuration.Formatters.First()
also results in the exception.
I am using this same method of accessing the "default" media type formatter in a custom ActionFilterAttribute
without any problems, why would this not also work in an AuthorizationFilterAttribute
?
Does anyone know how to access the configured media type formatters from an AuthorizationFilterAttribute
?
Note: I realize that I could have a way of specifying the media type formatter to use as part of the attribute initialization, but I was hoping that I would not have to do that and that I could just simply access the configured media type formatters. That and I am very curious as to why this isn't working.
Note 2: The version of the System.Web.Http DLL in use is 4.0.
Figured it out, turned out there was an assembly binding missing in the config file:
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With