开发者

Why is Request.ContentType always empty on my requests?

开发者 https://www.devze.com 2022-12-09 23:49 出处:网络
I have a base controller class that attempts to 开发者_StackOverflow中文版look at Request.ContentType to see if its a json request or a regular HTML request.The base controller then sets a simple enum

I have a base controller class that attempts to 开发者_StackOverflow中文版look at Request.ContentType to see if its a json request or a regular HTML request. The base controller then sets a simple enum on the base class and the appropriate controller returns the correct type. However, Request.ContentType is always an empty string. why is that?

my base controller:

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
    }
}

my 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."); }
});


It looks like you're trying to use the ContentType header to determine which type of response to return. That's not what it's for. You should be using the Accepts header instead, which tells the server which content types you accept.


Try using

 $.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/


The "content-type" header doesn't do anything when your method is "GET".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号