gpt4 book ai didi

asp.net - 在 ASP.NET MVC 3 中获取 ContentType

转载 作者:行者123 更新时间:2023-12-01 08:23:43 24 4
gpt4 key购买 nike

我有以下 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 的 Controller 方法中返回此结果对象:

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

}
}
});

请帮帮我。谢谢。

最佳答案

无法重现。这是我尝试过的:

结果:

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

Controller :

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 调用导致获取正确的请求内容类型。

关于asp.net - 在 ASP.NET MVC 3 中获取 ContentType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5644715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com