views:

216

answers:

2

Actually, I'm using this way. Do you have a better way?

private bool AcceptJson(HttpRequest request)
{
    const string JsonType = "application/json";

    if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith(JsonType))
    {
        return true;
    }

    if (request.AcceptTypes.Select(t => t.ToLower(CultureInfo.InvariantCulture) == JsonType).Count() > 0)
    {
        return true;
    }

    return false;
}
+1  A: 

That approach can lead to false positives (it doesn't account for q values or content types of which application/json is a substring).

You can find a decent Accept header parser in this article about XHTML. You'll have to port the algorithm to your language of choice and adapt it for the content-types you are using.

David Dorward
+1  A: 

It's tough to know what you mean by "better". Strictly speaking, you don't need to worry about the content type, so that can be removed. I guess technically a better way would be to remove the Select call and put the condition into the Count method.

Dan Goldstein