为什么Request.ContentType在我的请求中始终为空?
我有一个基本控制器类,它试图查看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."); }
});
它看起来像你想使用的ContentType头,以确定要返回的响应的类型。这不是它的目的。您应该使用Accepts标头,它会告诉服务器您接受哪些内容类型。
感谢捕捉。更改代码以搜索Request.AcceptTypes效果很好。 – ericvg 2009-10-29 14:27:06
“内容类型” 头没有做任何事情,当你的方法是 “GET”。
尝试使用
$.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/
抱歉替换了您的ShowVendor(数据);警报(数据); ...你可以修复,确定。 – MarkKGreenway 2009-10-26 16:32:27
也许内容类型设置后,你做这个检查。 – Trick 2009-10-26 16:29:41