Savaratkar
Savaratkar

Reputation: 2074

asp.net WebApi add MediaTypeFormatter in webconfig

I have a custom media formatter named TestFormatter in TestFormatter.cs extending MediaTypeFormatter. Now I want to add this formatter. One option is:

config.Formatters.Add(new BinaryMediaTypeFormatter());

what if I want to add this media type formatter in web.config file. I have seen

<webApi.webServer>
    <services>
      <replace serviceType="System.Web.Http.ExceptionHandling.IExceptionHandler, System.Web.Http" serviceClass="Slb.Avocet.WebApiServer.ExceptionHandling.GlobalExceptionHandler, Slb.Avocet.WebApiServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <replace serviceType="System.Web.Http.Description.IDocumentationProvider, System.Web.Http" serviceClass="Slb.Avocet.WebApiServer.Documentation.XmlDocumentationProvider, Slb.Avocet.WebApiServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </services>
    <mediaTypeFormatters>
    </mediaTypeFormatters>
    <messageHandlers>      
    </messageHandlers>
  </webApi.webServer>

node in web.config file. But i do not know the right syntax to add it. I have tried googling but no success.

Upvotes: 2

Views: 1008

Answers (1)

Sean O&#39;Brien
Sean O&#39;Brien

Reputation: 183

What you are trying to do cannot be done through the use of config file settings only; unfortunately, you will need to write some code to get where you want to be. This is because the web.config file is an ASP.NET / IIS construct and WebAPI was designed to be self-hosted (outside of IIS / ASP.NET).

I recommend adding your own custom ConfigurationSection to the config file. Add a MediaTypeFormatters property / element to your ConfigurationSection class, and have that property be a ConfigurationElementCollection. Then, in your website's Global.asax, add some code that copies any MediaTypeFormatters in your custom collection over to the "live" collection attached to HttpConfiguration. This link contains an example of using a similar approach to set the HttpConfiguration.IncludeErrorDetailPolicy property using web.config settings; while it's not exactly what you are trying to do it should provide a great starting point.

Upvotes: 1

Related Questions