ASP.NET,确定请求内容类型是否适用于 JSON

Ben*_*Ben 2 asp.net json content-type

我想在 HttpRequestBase 类型上实现扩展方法IsJsonRequest() : bool 。从广义上讲,这个方法应该是什么样子?是否有任何参考实现?

这是一个私有 API。

编辑:

建议; 检查 x-requested-with 标头是否为“xmlhttprequest”?

Lan*_*ney 5

这将检查几乎所有 javascript 框架都使用的内容类型和 X-Requested-With 标头:

public bool IsJsonRequest() {
    string requestedWith = Request.ServerVariables["HTTP_X_REQUESTED_WITH"] ?? string.Empty;
    return string.Compare(requestedWith, "XMLHttpRequest", true) == 0
        && Request.ContentType.ToLower().Contains("application/json");
}
Run Code Online (Sandbox Code Playgroud)