2009-10-26 1166 views
0

我有一個基本控制器類,它試圖查看Request.ContentType來查看它是一個json請求還是一個常規的HTML請求。基礎控制器然後在基類上設置一個簡單的枚舉,並且適當的控制器返回正確的類型。但是,Request.ContentType始終是一個空字符串。這是爲什麼?爲什麼Request.ContentType在我的請求中始終爲空?

我的基本控制器:

namespace PAW.Controllers 
{ 
    public class BaseController : Controller 
    { 
     public ResponseFormat ResponseFormat { get; private set; } 
     public User CurrentUser { get; private set; } 

     protected override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      base.OnActionExecuting(filterContext); 

      Culture.SetCulture(); 

      if (this.Request.ContentType.ToLower() == "application/json") 
       this.ResponseFormat = ResponseFormat.Json; 
      else 
       this.ResponseFormat = ResponseFormat.Html; 

      Response.Cache.SetCacheability(HttpCacheability.NoCache); 

      //setup user object 
      this.CurrentUser = WebUser.CurrentUser; 
      ViewData["CurrentUser"] = WebUser.CurrentUser; 
     } 
    } 

    public enum ResponseFormat 
    { 
     Html, 
     Json, 
     Xml 
    } 
} 

我的jquery:

$.ajax({ 
    type: "GET", 
    contentType: "application/json; charset=utf-8", 
    url: "/Vendor/Details/" + newid, 
    data: "{}", 
    dataType: "json", 
    success: function(data) { ShowVendor(data); }, 
    error: function(req, status, err) { ShowError("Sorry, an error occured (Vendor callback failed). Please try agian later."); } 
}); 
+0

也許內容類型設置後,你做這個檢查。 – Trick 2009-10-26 16:29:41

回答

2

它看起來像你想使用的ContentType頭,以確定要返回的響應的類型。這不是它的目的。您應該使用Accepts標頭,它會告訴服務器您接受哪些內容類型。

+0

感謝捕捉。更改代碼以搜索Request.AcceptTypes效果很好。 – ericvg 2009-10-29 14:27:06

0

「內容類型」 頭沒有做任何事情,當你的方法是 「GET」。

1

嘗試使用

$.ajax({ 
      type: "GET", 
      contentType: "application/json; charset=utf-8", 
      url: "/Vendor/Details/" + newid, 
      beforeSend: function(xhr) { 
       xhr.setRequestHeader("Content-type", 
        "application/json; charset=utf-8"); 
      }, 
      data: "{}", 
      dataType: "json", 
      success: function(data) { alert(data); }, 
      error: function(req, status, err) { ShowError("Sorry, an error occured (Vendor callback failed). Please try agian later."); } 
     }); 

一拉 - http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/

+0

抱歉替換了您的ShowVendor(數據);警報(數據); ...你可以修復,確定。 – MarkKGreenway 2009-10-26 16:32:27

相關問題