在ASP.NET中检测JSON请求的最好方法是什么

时间:2022-09-29 07:17:57

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

大多数ajax框架似乎都使用标头或查询字符串上的“X-Request-With”进行标准化。

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

在ASP。NET MVC可以使用扩展方法。

Request.IsAjaxRequest()

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

因为ajax客户机可以请求几种不同的内容类型,而不仅仅是“application/json”,例如:“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 static bool IsJsonRequest(this HttpRequestBase request)
{
    return request.Headers["Accept"].Split(',') 
       .Any(t => t.Equals("application/json", StringComparison.OrdinalIgnoreCase));
}

Thanks in advance.

提前谢谢。

6 个解决方案

#1


4  

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

为什么不能从发出请求的客户端传递bool变量IsJsonRequest呢?

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.

您可以为此使用请求的accept标头。这表示客户端希望服务器发送给它的内容类型。

#2


19  

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.

您应该使用这个请求的accept标头。这表示客户端希望服务器发送给它的内容类型。

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.

不要使用请求的内容类型标头——这表示请求消息体的类型。通过各种方法将其设置为“application / json”如果你发布或把一些json到服务器,但是如果你在做一个GET请求的内容类型应该是空的(就像一个GET请求的身体是空的),如果你发布一个多部分表单或其他东西就应该反映这类。

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.

web表单的行为是将请求内容类型设置为“multipart/form-data”,接受类型设置为“text/html”。在web上,重载服务器使其返回与请求内容类型相同的类型,而忽略accept类型标头将意味着已发布的表单返回编码的表单数据,而不是html页面。这显然不是正确的行为,所以不要在请求内容类型的解释周围构建应用程序。

#3


4  

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

我发现Pete Kirkham的答案非常有用。我认为这应该被标记为解。

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---

- - - - update - - -

Foollowing @Mvision suggestion this is the MVC version:

Foollowing @Mvision建议这是MVC版本:

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:

如果你需要在asp.net classic和MVC中使用这个方法,第二个是建议的方法。要在HttpREquestBase中转换HttpRequest,只需用HttpRequestWrapper包装它:

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

#4


1  

You can use

您可以使用

Request.IsAjaxRequest()

So you can check

所以你可以检查

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

#5


0  

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.

在任何你使用的控制器方法中。如果需要ActionFilterAttribute在多个地方执行工作,也可以将它放在ActionFilterAttribute中。

#6


0  

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));
    }
}

#1


4  

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

为什么不能从发出请求的客户端传递bool变量IsJsonRequest呢?

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.

您可以为此使用请求的accept标头。这表示客户端希望服务器发送给它的内容类型。

#2


19  

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.

您应该使用这个请求的accept标头。这表示客户端希望服务器发送给它的内容类型。

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.

不要使用请求的内容类型标头——这表示请求消息体的类型。通过各种方法将其设置为“application / json”如果你发布或把一些json到服务器,但是如果你在做一个GET请求的内容类型应该是空的(就像一个GET请求的身体是空的),如果你发布一个多部分表单或其他东西就应该反映这类。

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.

web表单的行为是将请求内容类型设置为“multipart/form-data”,接受类型设置为“text/html”。在web上,重载服务器使其返回与请求内容类型相同的类型,而忽略accept类型标头将意味着已发布的表单返回编码的表单数据,而不是html页面。这显然不是正确的行为,所以不要在请求内容类型的解释周围构建应用程序。

#3


4  

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

我发现Pete Kirkham的答案非常有用。我认为这应该被标记为解。

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---

- - - - update - - -

Foollowing @Mvision suggestion this is the MVC version:

Foollowing @Mvision建议这是MVC版本:

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:

如果你需要在asp.net classic和MVC中使用这个方法,第二个是建议的方法。要在HttpREquestBase中转换HttpRequest,只需用HttpRequestWrapper包装它:

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

#4


1  

You can use

您可以使用

Request.IsAjaxRequest()

So you can check

所以你可以检查

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

#5


0  

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.

在任何你使用的控制器方法中。如果需要ActionFilterAttribute在多个地方执行工作,也可以将它放在ActionFilterAttribute中。

#6


0  

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));
    }
}