ASP.NET Core 1.0 Web API 没有 return XML

ASP.NET Core 1.0 Web API doesn't return XML

如何让我的 vnext API 到 return XML 和 JSON?

我认为将内容类型与 application/xml 一起使用会像以前一样工作。 请注意,我也尝试使用 Accept : application/xml。

不过好像不是。

编辑:

这是我的 project.json 文件:

{
  "webroot": "wwwroot",
  "version": "1.0.0-*",

  "dependencies": {
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta4",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta4",
    "Microsoft.AspNet.Mvc": "6.0.0-beta4",
    "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta4"
  },

  "commands": {
      "web": "Microsoft.AspNet.Hosting --server     Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
  },

  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },

  "publishExclude": [
    "node_modules",
    "bower_components",
    "**.xproj",
    "**.user",
    "**.vspscc"
  ],
  "exclude": [
    "wwwroot",
    "node_modules",
    "bower_components"
  ]
}

这是我的 startup.cs :

public class Startup
{
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.ConfigureMvc(options =>
        {
            //options.AddXmlDataContractSerializerFormatter();

            options.InputFormatters.Add(new XmlSerializerInputFormatter());
            options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
        });
        services.AddMvc();
    }

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

您请求必须发送 AcceptHeader application/xml

Accept: Which media types are acceptable for the response, such as “application/json,” “application/xml,” or a custom media type such as "application/vnd.example+xml

内容类型定义您要发送的内容另请参阅 Difference between Accept and ContentType Header

我不确定 xml 的内容协商是否在 asp.net 5 webapi

中默认激活

看过这篇文章:Content Negotiation and Web API for the ASP.NET MVC Developer

默认情况下 Xml 格式化程序不包含在 Microsoft.AspNet.Mvc 包中。为此,您需要引用另一个名为 Microsoft.AspNet.Mvc.Xml 的包。

关于如何添加格式化程序的示例:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.ConfigureMvc(options =>
    {
        // This adds both Input and Output formatters based on DataContractSerializer
        options.AddXmlDataContractSerializerFormatter();

        // To add XmlSerializer based Input and Output formatters.
        options.InputFormatters.Add(new XmlSerializerInputFormatter());
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });

MVC 6 RespectBrowserAcceptHeader 默认为 false。因此它将绕过内容协商。这就是为什么在启用 XML 格式化程序后你可能总是得到 XML。

您可以通过将以下内容添加到您的启动文件来将 RespectBrowserAcceptHeader 设置为 true:

services.Configure<MvcOptions>(options =>
        {
            options.RespectBrowserAcceptHeader = true;
        });

这是 MVC6 rc1 的更新答案

Startup.cs(使用MvcXmlMvcBuilderExtensions

    public void ConfigureServices(IServiceCollection services)
    {
        var mvcBuilder = services.AddMvc();
        mvcBuilder.AddXmlSerializerFormatters();
        // or mvcBuilder.AddXmlDataContractSerializerFormatters()

project.json

"dependencies": {
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final",

不要忘记,因为 ASP.NET 5 已重命名为 ASP.NET Core 1.0,因此 Microsoft.AspNet.Mvc 变成了 Microsoft.AspNetCore.Mvc

"dependencies": {
   "Microsoft.AspNetCore.Mvc" : "1.0.2",
   "Microsoft.AspNetCore.Mvc.Formatters.Xml" : "1.0.2",

这在 RC2 中被简化为 services.AddMvc().AddXmlDataContractSerializerFormatters();

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            services.AddMvc().AddXmlDataContractSerializerFormatters();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

.Net Core 1.0.0 发布后更新的详细信息

startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(config =>
    {
        // Add XML Content Negotiation
        config.RespectBrowserAcceptHeader = true;
        config.InputFormatters.Add(new XmlSerializerInputFormatter());
        config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });

project.json

"dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Mvc.Formatters.Xml": "1.0.0",

如需更多帮助,请参阅有关主题的 Shawn Wildermuths 博客 post:Content Negotiation in ASP.NET Core

面对类似的问题,必须在一个 WEB REST API 服务中处理,使用 ASP .NET MVC Core 1.1.0,两种类型的 XML 正文请求 DataContractSerializerXmlSerializer

因此,在我的情况下,我需要 FromXmlBodyXmlResult 以及 XML连载。

阅读此线程并考虑通过变通来编写代码的和平,但是当我查看 GitHub 时。我发现解决方案已经存在。

我检查过,它看起来像是一个高质量的软件工程解决方案。

我想分享链接: 这是 Asp.NET 核心版本的新 XML 扩展。 >=1.1.0 XmlResult 和 FromXmlASP.NET 核心 MVC 格式化程序的主体扩展,用于 XML 使用 DataContractSerializer 和 XmlSerializer 输入和输出。

https://github.com/Wallsmedia/XmlResult

金块包:https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Formatters.Xml.Extensions

它在一个 service/controller/method 中适用于两种类型的 Xml 序列化类型(DataContractSerializer 和 XmlSerializer)。 这是示例:

 [Route("api/[controller]")]
public class XmlExtController : Controller
{
    // GET api/[controller]/xml
    [HttpGet("xml")]
    public ActionResult GetXmlObject()
    {
        object obj = new PurchaseOrder();
        return new XmlResult(obj);
    }

    // GET api/[controller]/dcxml
    [HttpGet("dcxml")]
    public ActionResult GetDcXmlObject()
    {
        object obj = new PurchaseOrder();
        return new XmlResult(obj) { XmlSerializerType = XmlSerializerType.DataContractSerializer };
    }

    // POST api/[controller]/xml
    [HttpPost("xml")]
    public void PostXml([FromXmlBody]PurchaseOrder value)
    {
        var x = value;
        x.billTo.street += " 123";
    }

    // POST api/[controller]/dcxml
    [HttpPost("dcxml")]
    public void PostDcXml([FromXmlBody(XmlSerializerType = XmlSerializerType.DataContractSerializer)]PurchaseOrder value)
    {
        var x = value;
        x.billTo.street += "No -10";
    }

}

ASP.NET Core 1.1 的更新答案:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(config => {
        config.RespectBrowserAcceptHeader = true;
        config.InputFormatters.Add(new XmlSerializerInputFormatter());
        config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });            
}

Csproj:

<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="1.1.3" />