Removing the XML Formatter from ASPNET Web API Applications, to Json/p result

Posted: August 19, 2014 in .net, c#, Uncategorized, web api
Tags: , , ,
Code:
    ///In filters register:
    // This method allows the client to override their browser's HTTP Accept header by putting a value in the querystring.
    //...
    GlobalConfiguration.Configuration.Filters.Add(new FormattingOverrideFilterAttribute(formatPreferenceOverride: "application/json", clearOtherPreferredMediaTypes: true));
    //...
///...

public class FormattingOverrideFilterAttribute : ActionFilterAttribute{
    /// <summary>
    /// Allows overriding the Accept header by querystring or server preference.
    /// </summary>
    /// <param name="formatPreferenceOverride">If defined, this mime type will be injected into the Accept header of every request.</param>
    /// <param name="newQuality">Optional, The quality setting for this media type. Should be between 1 and 0.</param>
    /// <param name="clearOtherPreferredMediaTypes">If true, will remove all other media types from the Accept header.</param>
    public FormattingOverrideFilterAttribute(string formatPreferenceOverride = null, double? newQuality = null, bool clearOtherPreferredMediaTypes = false) : base() {
        NewQualityValue = newQuality;
        FormatPreferenceOverride = formatPreferenceOverride;
        ClearOtherPreferredMediaTypes = clearOtherPreferredMediaTypes;
    }

    public double? NewQualityValue { get; set; }
    public string FormatPreferenceOverride { get; set; }
    public bool ClearOtherPreferredMediaTypes { get; set; }

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) {
        var qs = actionContext.Request.RequestUri.ParseQueryString();

        var requestedMediaType = (qs["f"] ?? qs["format"] ?? FormatPreferenceOverride ?? String.Empty).ToLower();

        switch (requestedMediaType) {
            case "xml":
            case "x":
                requestedMediaType = "application/xml";
                break;
            case "j":
            case "js":
            case "json":
                requestedMediaType = "application/json";
                break;
        }

        if (String.IsNullOrEmpty(requestedMediaType))
            return; // No action is necessary because no override was requested.

        var acceptHeaders = actionContext.Request.Headers.Accept;
        MediaTypeWithQualityHeaderValue header = null;

        if (ClearOtherPreferredMediaTypes) {
            var newAcceptHeaders = acceptHeaders.Where(h => h.MediaType == requestedMediaType || h.MediaType == "*/*").ToList();
            acceptHeaders.Clear();
            newAcceptHeaders.ForEach(acceptHeaders.Add);
        }

        header = acceptHeaders.FirstOrDefault(h => h.MediaType == requestedMediaType);
        if (header == null) {
            header = new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(requestedMediaType);
            acceptHeaders.Add(header);
        }

        System.Diagnostics.Debug.WriteLine("Overidding HttpAccept header for format preference.");
        header.Quality = NewQualityValue;
    }
}

Sources:

Best—> http://weblog.west-wind.com/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API

Another…. ->http://weblog.west-wind.com/posts/2012/Mar/09/Removing-the-XML-Formatter-from-ASPNET-Web-API-Applications

Advertisements
Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s