我在c#中有以下代码。我正在使用ASP.NET MVC 3.在ASP.NET MVC 3中获取ContentType
public override void ExecuteResult(ControllerContext context)
{
// If ContentType is not expected to be application/json, then return XML
if ((context.HttpContext.Request.ContentType ?? String.Empty).Contains("application/json"))
{
new JsonResult { Data = this.Data }
.ExecuteResult(context);
}
else
{
using (MemoryStream stream = new MemoryStream(500))
{
using (var xmlWriter = XmlTextWriter.Create(
stream,
new XmlWriterSettings()
{
OmitXmlDeclaration = true,
Encoding = UTF8,
Indent = true
}))
{
new XmlSerializer(typeof(T), IncludedTypes)
.Serialize(xmlWriter, this.Data);
}
// NOTE: We need to cache XmlSerializer for specific type. Probably use the
// GenerateSerializer to generate compiled custom made serializer for specific
// types and then cache the reference
new ContentResult
{
ContentType = "text/xml",
Content = UTF8.GetString(stream.ToArray()),
ContentEncoding = UTF8
}
.ExecuteResult(context);
}
}
}
我试图根据请求返回json或xml结果。问题是我运行时得到context.HttpContext.Request.ContentType = ""
。
有没有办法让应用程序知道请求是“application/json”?
我回国的控制器方法称为GetGoogleMapsMarkers这个结果对象:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://localhost:1939/API/Google/GetGoogleMapsMarkers",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
}
});
请帮助我。 谢谢。
嗨,我tryed你做了什么,但现在我获取'text/html'而不是'application/json'... – OscarVGG 2011-04-13 16:43:21