2011-04-13 70 views
1

我在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); 

     } 
    } 
}); 

请帮助我。 谢谢。

回答

1

我加入

data: { },

到Ajax调用和它的工作....这是奇怪,但它使人们的工作...

2

无法重现。下面是我的尝试:

结果:

public class TestResult : ActionResult 
{ 
    public override void ExecuteResult(ControllerContext context) 
    { 
     var ct = context.HttpContext.Request.ContentType; 
     context.HttpContext.Response.Write(ct); 
    } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult Foo() 
    { 
     return new TestResult(); 
    } 
} 

查看:

<script type="text/javascript"> 
    $.ajax({ 
     url: '@Url.Action("foo")', 
     type: 'POST', 
     contentType: 'application/json; charset=utf-8', 
     success: function (result) { 
      alert(result); 
     } 
    }); 
</script> 

AJAX调用导致正确的请求的内容类型是牵强。

+0

嗨,我tryed你做了什么,但现在我获取'text/html'而不是'application/json'... – OscarVGG 2011-04-13 16:43:21