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

4
  • Rather than adding the headers, can't you just make the default return type XML? Or would that break other clients maybe? Commented Nov 9, 2017 at 10:05
  • 1
    related, but the opposite problem, so not strictly a duplicate... stackoverflow.com/questions/36492004/… (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) Commented Nov 9, 2017 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 social.msdn.microsoft.com/Forums/vstudio/en-US/… Commented Nov 9, 2017 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 Commented Nov 9, 2017 at 10:15

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.