开发者

What's the best way to detect a JSON request on ASP.NET

Most ajax frameworks seem to standardize with "X-Request-With" on either a header or the query string.

And in ASP.NET MVC you can use the extension method

Request.IsAjaxRequest()

Because an ajax client can request several different content types, not just "application/json" ex: "application/xml".

I'm using the following code snippet/extension method, but I would love to see what others are doing or if there is something I missed, or a better way.

public st开发者_StackOverflowatic bool IsJsonRequest(this HttpRequestBase request)
{
    return request.Headers["Accept"].Split(',') 
       .Any(t => t.Equals("application/json", StringComparison.OrdinalIgnoreCase));
}

Thanks in advance.


You should be using the request's accept header for this. This indicates what type of content the client wants the server to send to it.

Do not use the request's content type header - this indicates is the type of the body of the request message. By all means set it to "application/json" if you are POSTing or PUTting some Json to the server, but if you are making a GET request then the content type should be empty ( as the body of a GET request is empty ), and if you are posting a multi-part form or something else then it should reflect that type.

The behaviour for forms on web is to set the request content type to 'multipart/form-data' and the accept type to 'text/html'. On the web, overloading the server so that it returns the same type as the request content type whilst ignoring the accept type header would mean that posted forms return encoded form data rather than an html page. This obviously is not the correct behaviour, so don't build your applications around such an interpretation of the request content type.


I found the Pete Kirkham answer very useful. And I think that should be marked as solution.

This is my code according it:

/// <summary>
/// Determines whether the request is a Json Request
/// </summary>
public static bool GetIsJsonRequest(HttpRequest request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }
    bool rtn = false;
    const string jsonMime = "application/json";

    if (request.AcceptTypes!=null)
    {
        rtn = request.AcceptTypes.Any(t => t.Equals(jsonMime, StringComparison.OrdinalIgnoreCase));
    }
    return rtn || request.ContentType.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries).Any(t => t.Equals(jsonMime, StringComparison.OrdinalIgnoreCase));
}

---UPDATE---

Foollowing @Mvision suggestion this is the MVC version:

public static bool GetIsJsonRequest(HttpRequestBase request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }
    bool rtn = false;
    const string jsonMime = "application/json";

    if (request.AcceptTypes!=null)
    {
        rtn = request.AcceptTypes.Any(t => t.Equals(jsonMime, StringComparison.OrdinalIgnoreCase));
    }
    return rtn || request.ContentType.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries).Any(t => t.Equals(jsonMime, StringComparison.OrdinalIgnoreCase));
}

If you need to use this method in both asp.net classic and MVC the second is the suggested one. To convert HttpRequest in HttpREquestBase just wrap it with HttpRequestWrapper:

public static bool GetIsJsonRequest(HttpRequest request)
{
    return GetIsJsonRequest(new HttpRequestWrapper(request));
}


Why cant you just pass a bool variable say IsJsonRequest from the client where you are making request?

Then make a check in action method.

or

You could use the request's accept header for this. This indicates what type of content the client wants the server to send to it.


You can use

Request.IsAjaxRequest()

So you can check

if (Request.IsAjaxRequest())
{
   return new JsonResult();
}
return ActionResult


You can use

Request.ContentType 

in whatever controller method you are using. You can also place this in an ActionFilterAttribute if you need it to do work in multiple places.


Hope this will be much more efficient

public static class JsonResultController
{
    public static bool IsJsonRequest(this HttpRequestBase request)
    {
        return GetIsJsonRequest(request);
    }

    public static bool IsJsonRequest(this HttpRequest request)
    {
        return GetIsJsonRequest(request);
    }

    private static bool GetIsJsonRequest(dynamic request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }
        bool rtn = false;
        const string jsonMime = "application/json";

        if (request.AcceptTypes != null)
        {
            rtn = (request.AcceptTypes as string[]).Any(t => t.Equals(jsonMime, StringComparison.OrdinalIgnoreCase));
        }
        return rtn || (request.ContentType as string ?? "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Any(t => t.Equals(jsonMime, StringComparison.OrdinalIgnoreCase));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜