Forcing accept type for WebApi call

Setting accept type on the server side for the WebApi request

One of the coolest things of WebApi is that adapts to accept type sent in request header. This header value depends on a client.

Based on this WebApi will serve different formats of data (XML/JSON).

The problems start when you need to force a type of data to be returned. You can do this very easy on a clinet side if you are invoking REST service method from JQuery.

$.ajax({
	url: "/ApiController/Method",
    method: "GET",
    dataType: "text xml",
    accepts: {
        xml: "text/xml"
    },
	success: function (data) {
    
    }
});
    

This is fine in case you fetch the data witha a request managed by JQuery.

In cases you have to return data directly inta browser, if your method is exposed as a link on a page, you are pretty much depending on a browser headers. This might case some issue in case you need to return the same type for every browser. 

For example, if you are exposing RSS feed as a link on your web page, client will get the feed if he is accessing from Firefox but in case client is accessing from IE 11, he might get an empty JSON string { } even though you used Rss20FeedFormatter as a return type of your class.

	public class RssFeedController : ApiController
    {
        public Rss20FeedFormatter GetFeed()
        {
            SyndicationFeed feed = new SyndicationFeed();
			//Fill up the feed data
			
			return new Rss20FeedFormatter(feed);
		}
	}
    

Luckily WebApi enables bunch of attributes you can attach to a method which can affect method behavior. My friend and a college @miloshfirst came up with and idea to use this for the purpose of forcing WebApi method return type in cases where we do not set headers of a request on a client side (using direct link on a page).

public class ReturnXmlOnly : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {

            actionContext.Request.Headers.Accept.Clear();
            actionContext.Request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml"));
        }
    }
    

This action filter attribute will set accept type headers on a request itself on server side. Simple adding of this custom attribute to a method signature in controller will make every method invoke and XML result in a response.

	public class RssFeedController : ApiController
    {
        [ReturnXmlOnly]
        public Rss20FeedFormatter GetFeed()
        {
            SyndicationFeed feed = new SyndicationFeed();
			//Fill up the feed data
			
			return new Rss20FeedFormatter(feed);
		}
	}
    

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article