Is there a better way to verify if a request accepts JSON?

By : Zote
Source: Stackoverflow.com
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;
}
By : Zote


Answers

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.

By : Quentin


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.



setters actually have very little to do with object orientation, which is the programming idiom applied in the example. getters are marginally better, but can be lived without in many cases. If everything can be gotten and set, what's the point of having an object? Operations should be called on objects to accomplish things, changing the internal state is merely a side-effect of this. The bad thing about a setter in the presence of polymorphism - one of OO's cornerstones - is that you force every derived class to have a setter. What if the object in question has got no need for an internal state called mIsVisible? Sure he can ignore the call and implement as empty, but then you are left with a meaningless operation. OTOH, operations like show and hide can be easily overridden with different implementations, without revealing anything about the internal state.

By : QBziZ


This video can help you solving your question :)
By: admin