为什么Request.ContentType在我的请求中总是为空?

时间:2009-10-26 16:16:36

标签: jquery asp.net-mvc

我有一个基本控制器类,它试图查看Request.ContentType以查看它是json请求还是常规HTML请求。然后,基本控制器在基类上设置一个简单的枚举,并且相应的控制器返回正确的类型。但是,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."); }
});

3 个答案:

答案 0 :(得分:2)

看起来您正在尝试使用ContentType标头来确定要返回的响应类型。这不是它的用途。您应该使用Accepts标头,它告诉服务器您接受哪些内容类型。

答案 1 :(得分: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."); }
        });

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

答案 2 :(得分:0)

当您的方法为“GET”时,“content-type”标头不会执行任何操作。