Example IsJsonRequest()

While doing some ASP.NET MVC Json programming today I discovered there is still no standard extension method for checking whether a request specifically wants a Json result.

I wanted to support both the mime type as well as a ‘format’ parameter in the url.

Here is the extension method I wrote:


public static class JsonRequestExtensions
{
    private const string format = "format";
    private const string json = "json";
    private const string jsonMime = "application/json";

    public static bool IsJsonRequest( this HttpRequestBase request )
    {

        bool isJsonRequest = ( IsRequestedFormatJson( request ) == true
                               ||
                               IsRequestedMimeTypeJson( request ) == true );

        return isJsonRequest;
    }

    private static bool IsRequestedMimeTypeJson( HttpRequestBase request )
    {
        if ( request.AcceptTypes != null )
        {
            return request.AcceptTypes.Any( t => t.Equals( jsonMime, StringComparison.OrdinalIgnoreCase ) );
        }
        return false;
    }

    private static bool IsRequestedFormatJson( HttpRequestBase request )
    {
        return String.Equals( request[format], json, StringComparison.OrdinalIgnoreCase );
    }
}

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