Question

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;
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top