我想在 HttpRequestBase 类型上实现一个扩展方法 IsJsonRequest() : bool 。从广义上讲,这个方法应该是什么样子?有没有任何参考实现?
这是一个私有API。
编辑:
建议;检查 x-requested-with 标头是否为“xmlhttprequest”?
这将检查内容类型和 X-Requested-With 标头,几乎所有 javascript 框架都使用:
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");
}
我遇到了同样的问题,但无论出于何种原因,jQuery 的 $.get 没有发送内容类型。相反,我必须检查“application/json”的 Request.AcceptTypes。
希望这可以帮助其他人将来遇到同样的问题。
由于它是私有 API,您可以控制 JSON 的内容类型,因此只需检查它是否是约定的值即可。
例如
public static bool IsJsonRequest(this HttpRequestBase request)
{
bool returnValue = false;
if(request.ContentType == "application/json")
returnValue = true;
return returnValue;
}
ContentType 可以有除 application/json 之外的其他值,Mozila here
request.ContentType?.ToLowerInvariant().Contains(System.Net.Mime.MediaTypeNames.Application.Json)