我想在HttpRequestBase類型上實現擴展方法IsJsonRequest():bool。廣義地說,這個方法應該是什麼樣子,並且有沒有任何參考實現?ASP.NET,確定請求內容類型是否爲JSON
這是一個私人API。
編輯:
建議;檢查x-requested-header是否爲「xmlhttprequest」?
我想在HttpRequestBase類型上實現擴展方法IsJsonRequest():bool。廣義地說,這個方法應該是什麼樣子,並且有沒有任何參考實現?ASP.NET,確定請求內容類型是否爲JSON
這是一個私人API。
編輯:
建議;檢查x-requested-header是否爲「xmlhttprequest」?
這將檢查內容類型和X-要求,隨着其pretty much all javascript frameworks use頭:
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");
}
由於它是一個私有API,因此您可以控制JSON的內容類型,因此只需檢查它是商定的值即可。
例如
public static bool IsJsonRequest(this HttpRequestBase request)
{
bool returnValue = false;
if(request.ContentType == "application/json")
returnValue = true;
return returnValue;
}
我有同樣的問題,但無論出於何種原因jQuery的$不用彷徨不發送內容類型。相反,我必須檢查「application/json」的Request.AcceptTypes。
希望這可以幫助其他人在將來遇到同樣的問題。
注意:如果我正確閱讀,Content-Type標頭指定**請求**的格式 - 它與客戶端期望得到的內容無關 - 這將是Accept標頭:http: //en.wikipedia.org/wiki/List_of_HTTP_header_fields – Kobi 2012-03-22 08:15:20