0

<?xml ... />カスタムメイドの XML 文字列を返すコントローラーを用意しました。これは、API を使用するアプリケーションが、属性やデフォルトの 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

この記事はあなたが探しているもののようです。手動で行う代わりに、次のように 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 のFormattersに関するこの非常に詳細な記事も確認してください。これは更新されたバージョンです。参考になると思います。

応答が生成される方法を変更するには、次のように XmlWriterSettings オプション オブジェクトを使用できます (詳細はこちら)。

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

それが役に立てば幸い!

于 2016-03-17T08:10:04.387 に答える
0

XmlWriterパディング オプションを作成して、XML 宣言の作成をブロックします。次に 、.XmlSerializer.Serializeを取るオーバーロードの 1 つを使用します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 に答える