gpt4 book ai didi

xml - 返回 "application/xml"而不是 "text/plain"ASP.NET Core Web API

转载 作者:数据小太阳 更新时间:2023-10-29 01:41:19 24 4
gpt4 key购买 nike

我有一个 XML 字符串,我需要将它作为 XML 文档返回。默认情况下,返回内容类型为 text/plain。内容已呈现,但我需要内容类型为 application/xml。我启用了 RespectBrowserAcceptHeader 选项,它将对象序列化为 XML 并设置正确的内容类型,除非对象是字符串。

[HttpGet]
public string Get()
{
return xmlString;
}

public static string xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<sample>
Hello World.
</sample>";

最佳答案

简答

如果您有一个 XML 字符串并且需要将其作为 XML 文档返回,则返回 ContentResult .

[HttpGet]
public ContentResult Get()
{
return new ContentResult
{
ContentType = "application/xml",
Content = xmlString,
StatusCode = 200
};
}

完整示例

Controller

using Microsoft.AspNetCore.Mvc;

namespace MyXmlSample
{
[Route("xml")]
public class MyXmlController
{
public static string xmlString =

@"<?xml version=""1.0"" encoding=""UTF-8""?>
<sample>
Hello World.
</sample>";

[HttpGet]
public ContentResult Get()
{
return new ContentResult
{
ContentType = "application/xml",
Content = xmlString,
StatusCode = 200
};
}
}
}

启动

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace MyXmlSample
{
public class Program
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
}

public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}

public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Program>()
.Build();

host.Run();
}
}
}

project.json

{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.AspNetCore.Mvc.Core": "1.0.0-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.NETCore.App": "1.0.0-rc2-*"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dnxcore50",
"portable-net45"
]
}
},
"runtimes": {
"win10-x64": {}
}
}

响应

HTTP/1.1 200 OK
Date: Sun, 17 Apr 2016 22:10:45 GMT
Content-Type: application/xml
Server: Kestrel
Content-Length: 75

<?xml version="1.0" encoding="UTF-8"?>
<sample>
Hello World.
</sample>

Here it is on GitHub为了好的措施。 :)

关于xml - 返回 "application/xml"而不是 "text/plain"ASP.NET Core Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682240/

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