0

我有一个控制器,它返回一个定制的 XML 字符串,因为使用 Api 的应用程序需要一种特定格式,没有任何属性,并且<?xml ... />默认 XML 字符串顶部没有标签。编辑:消费者也没有请求“text/xml”的请求标头。

我的 Startup.cs 中的 ConfigureServices 如下所示:

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        var mvc = services.AddMvc();

        mvc.AddMvcOptions(options =>
        {
            options.InputFormatters.Remove(new JsonInputFormatter());
            options.OutputFormatters.Remove(new JsonOutputFormatter());
        });

        mvc.AddXmlDataContractSerializerFormatters();
    }

在我的控制器中,我尝试了一些我在互联网上找到的解决方案(已注释掉),但没有一个在 chrome devtools 中给我带有响应标头“Content-Type:application/xml”的 XML 内容:

[HttpGet("{ssin}")]
[Produces("application/xml")]
public string Get(string ssin)
{    
    var xmlString = "";
    using (var stream = new StringWriter())
    {
        var xml = new XmlSerializer(person.GetType());
        xml.Serialize(stream, person);
        xmlString = stream.ToString();
    }
    var doc = XDocument.Parse(xmlString);
    doc.Root.RemoveAttributes();
    doc.Descendants("PatientId").FirstOrDefault().Remove();
    doc.Descendants("GeslachtId").FirstOrDefault().Remove();
    doc.Descendants("GeboorteDatumUur").FirstOrDefault().Remove();
    doc.Descendants("OverledenDatumUur").FirstOrDefault().Remove();
    Response.ContentType = "application/xml";
    Response.Headers["Content-Type"] = "application/xml";

    /*var response = new HttpResponseMessage
    {
        Content = new  StringContent(doc.ToString(), Encoding.UTF8, "application/xml"),
    };*/
    return doc.ToString(); //new HttpResponseMessage { Content = new StringContent(doc., Encoding.UTF8, "application/xml") };
}

我可以尝试什么让它响应 application/xml? 回复

EDIT1(在 Luca Ghersi 的回答之后): Startup.cs:

    public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        var mvc = services.AddMvc(config => {
            config.RespectBrowserAcceptHeader = true;
            config.InputFormatters.Add(new XmlSerializerInputFormatter());
            config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
        });

        mvc.AddMvcOptions(options =>
        {
            options.InputFormatters.Remove(new JsonInputFormatter());
            options.OutputFormatters.Remove(new JsonOutputFormatter());
        });

        //mvc.AddXmlDataContractSerializerFormatters();
    }
    /*
     * Preconfigure if the application is in a subfolder/subapplication on IIS
     * Temporary fix for issue: https://github.com/aspnet/IISIntegration/issues/14 
     */
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.Map("/rrapi", map => ConfigureApp(map, env, loggerFactory));
    }


    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void ConfigureApp(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        //app.UseIISPlatformHandler();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    // Entry point for the application.
    public static void Main(string[] args) => WebApplication.Run<Startup>(args);

控制器:

        [HttpGet("{ssin}")]
    [Produces("application/xml")]
    public IActionResult Get(string ssin)
    {
        var patient = db.Patienten.FirstOrDefault(
            p => p.Rijksregisternummer.Replace(".", "").Replace("-", "").Replace(" ", "") == ssin
        );

        var postcode = db.Postnummers.FirstOrDefault(p => p.PostnummerId == db.Gemeentes.FirstOrDefault(g =>
            g.GemeenteId == db.Adressen.FirstOrDefault(a =>
                a.ContactId == patient.PatientId && a.ContactType == "pat").GemeenteId
            ).GemeenteId
        ).Postcode;

        var person = new person
        {
            dateOfBirth = patient.GeboorteDatumUur.Value.ToString(""),
            district = postcode,
            gender = (patient.GeslachtId == 101 ? "MALE" : "FEMALE"),
            deceased = (patient.OverledenDatumUur == null ? "FALSE" : "TRUE"),
            firstName = patient.Voornaam,
            inss = patient.Rijksregisternummer.Replace(".", "").Replace("-", "").Replace(" ", ""),
            lastName = patient.Naam
        };
        var xmlString = "";
        using (var stream = new StringWriter())
        {
            var opts = new XmlWriterSettings { OmitXmlDeclaration = true };
            using (var xw = XmlWriter.Create(stream, opts))
            {
                var xml = new XmlSerializer(person.GetType());
                xml.Serialize(xw, person);
            }
            xmlString = stream.ToString();
        }
        var doc = XDocument.Parse(xmlString);
        doc.Root.RemoveAttributes();
        doc.Descendants("PatientId").FirstOrDefault().Remove();
        doc.Descendants("GeslachtId").FirstOrDefault().Remove();
        doc.Descendants("GeboorteDatumUur").FirstOrDefault().Remove();
        doc.Descendants("OverledenDatumUur").FirstOrDefault().Remove();

        return Ok(doc.ToString()); 
4

2 回答 2

0

创建XmlWriter填充选项以阻止创建 XML 声明。然后使用一个 XmlSerializer.Serialize需要XmlWriter. XmlWriter可以写入字符串(请参见此处

using (var sw = new StringWriter()) {
  var opts = new XmlWriterSettings { OmitXmlDeclaration = true };
  using (var xw = XmlWriter.Create(sw, opts) {

    xml.Serialize(xw, person);

  }
  xmlString = sw.ToString();
}

注意Response.ContentType如果覆盖它,您已经在设置其他内容。检查可能覆盖您的设置的过滤器和模块。

于 2016-03-17T08:15:26.263 回答
0

看起来这篇文章就是你要找的。您应该尝试使用 XML 格式化程序,而不是尝试手动执行此操作,如下所示:

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

此 outputFormatter 取决于:

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

此外,您需要保留此答案[Produces("application/xml")]中详述的方法属性。

还可以查看这篇关于MVC 6 中格式化程序的非常详细的文章。它是更新版本。我想这会有所帮助。

要修改响应的生成方式,您可以使用 XmlWriterSettings 选项对象,如下所示(更多信息here):

var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
config.OutputFormatters.Add(new XmlSerializerOutputFormatter(settings);

希望能帮助到你!

于 2016-03-17T08:10:04.387 回答