0

I have written a RESTful web service using MVC4 Web API. One of the clients that is calling my web service is posting an XML body, but getting a JSON response.

I have learned that the client is not setting the header value of Content-type: application/xml or Accept: application/xml.

The client who is calling my web service is one of the largest companies in the world and refuses to add the required header values.

So my question is, how do I add the missing header values that the client is not sending so that my web service can return a response in XML?

Or how do I get my web service to response in XML with missing?

I have tried adding the following to the Global.asax.cs;

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.HttpMethod == "POST" 
            && HttpContext.Current.Request.CurrentExecutionFilePath.Contains("OrderInformation"))
        {
            HttpContext.Current.Request.Headers.Add("content-type", "application/xml");
            HttpContext.Current.Request.Headers.Add("Accept", "application/xml");
        }
    }

But an exception is throw at runtime.

TIA

Matt

Matt Puleston
  • 95
  • 1
  • 2
  • 8
  • Rather than adding the headers, can't you just make the default return type XML? Or would that break other clients maybe? – GPW Nov 09 '17 at 10:05
  • 1
    related, but the opposite problem, so not strictly a duplicate... https://stackoverflow.com/questions/36492004/webapi-mvc-4-set-default-response-type (EDIT: I think it comes down to the order in which you specify the formatters in the config as per the link? Untested so could be wrong) – GPW Nov 09 '17 at 10:11
  • I am not sure how to do in MVC but you should be able to override some classes and modify incoming request headers as required. Following link is related to WCF but similar should be possible using MVC https://social.msdn.microsoft.com/Forums/vstudio/en-US/3b9a93a1-4406-416e-b328-1e0b626e563d/how-to-intercept-wcf-raw-messages?forum=wcf – Softec Nov 09 '17 at 10:11
  • If 'largest' company don't know how to use content negotiation in 2017, you can simply provide to them separate endpoint. Something like `/orders/foo.xml` then use solution suggested by GPW – Sergey Berezovskiy Nov 09 '17 at 10:15

1 Answers1

0

Thanks GPW. your link help, I've created a DelegatingHandler to correct the request header

public class MediaTypeDelegatingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var url = request.RequestUri.ToString();

        if (url.Contains("OrderInformation"))
        {
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
Matt Puleston
  • 95
  • 1
  • 2
  • 8