In this short tutorial, we are going to see how to restrict different requests for different media types in Web API. In reality, a generic Web API needs to support different Content-types to provide interoperability for different platforms. By default, ASP.Net Web API supports JSON and XML formatters, and we can add additional formatters by implementing MediaTypeFormatter class. But lets take a particular requirement where we need to only support application/json and all other requests should be invalidated. In that case first we have to remove support for all other different formatters in our Web API. Then we need to check HttpRequestMessage for its Accept headers, if that request is made for application/json we are going to serve it or else a HttpExceptionMessage has to be raised.
IMPORTANT – I am going to continue the code from where I left out in my last tutorial. For better understanding, please check out my previous tutorial step by step – http://www.intstrings.com/ramivemula/tag/asp-net-web-api/
Lets first start by removing all additional formatters available for our Web API. For that add the following piece of code to Application_Start() in Global.asax. Below code removes Xml, FormUrlEncoded and JQueryMvcFormUrlEncoded formatters support.
var config = GlobalConfiguration.Configuration; var jqueryFormatter = config.Formatters.FirstOrDefault(x => x.GetType() == typeof(JQueryMvcFormUrlEncodedFormatter)); config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter); config.Formatters.Remove(jqueryFormatter);
Now lets create an Extension method for HttpRequestMessage to check whether accept headers only have application/json, and next all other different types will be invalidated. Create a class in Utils folder with name ExtensionMethods and place the following code in there –
IMPORTANT: Some of the extension methods – ParseProductString and ReplaceExtraQuotes are irrelevant for present tutorial. But I used them in my last tutorial – Create Custom Media Formatter. Please note that I refactored code from last tutorial to present tutorial, I moved these extension methods to Utils Folder/ExtensionMethods class which are previously in MediaTypeFormatter class file.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net.Http; namespace BasicWebApi1.Utils { public static class ExtensionMethods { public static bool CheckAcceptHeader(this HttpRequestMessage request) { if (request.Headers.Accept == null) return false; if (request.Headers.Accept.ToString() == String.Empty) return false; if (request.Headers.Accept.ToString() != "application/json") return false; if (request.Headers.Accept.ToString() == "application/json") return true; return false; } public static string ParseProductsString(this string original) { return original.Replace("][", "}{") .Replace("[", string.Empty) .Replace("]", string.Empty); } public static string ReplaceExtraQuotes(this string original) { return original.Replace("\"", String.Empty); } } }
Now lets modify the Products Controller GET Products action to validate incoming HttpRequestMessage –
[HttpGet] public IEnumerable<Product> GetProducts() { if (!this.Request.CheckAcceptHeader()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); return _products; }
Lets test our GET Action with application/xml request from fiddler –
Image may be NSFW.
Clik here to view.
As we requested for application/xml, our action is going to throw Unsupported Media type exception –
Image may be NSFW.
Clik here to view.
Lets make a valid request for application/json media type –
Image may be NSFW.
Clik here to view.
With above request, we get following response –
Image may be NSFW.
Clik here to view.