在ASP.NET MVC 3中获取ContentType

时间:2011-04-13 05:14:13

标签: asp.net asp.net-mvc-3 jquery

我在c#中有以下代码。我正在使用ASP.NET MVC 3。

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

        }
    }
});

请帮帮我。 感谢。

2 个答案:

答案 0 :(得分: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调用导致获取正确的请求内容类型。

答案 1 :(得分:1)

我添加了

data: { },

到ajax调用它起作用....这很奇怪,但它使它工作......