.net core miscellanea: WebAPI XML requests and responses

Under normal circumstances, restfult api return data or model binding, the default json format would be more common and convenient, of course, occasionally need XML format requirements

For the return XML, plain common way is to serialize such as XmlFormatter in each aciton method,

For receiving XML, it is some additional XML parsing operation or deserialization process.

The following records and learn more convenient WebAPI the XML request and response processing use, do not like do not spray, wrong Please advise.

.net core version: 2.2

Adding XML format support

1, the installation package Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet

2, then Startup.ConfigureServices call AddXmlSerializerFormatters configures the implementation of the System.Xml.Serialization.XmlSerializer.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddXmlSerializerFormatters();
}

Response XML data

Action level want to specify a particular operation within the XML format in response Controller level or globally, just add [Produces]  filter, will go into the xml format in response to processing, without further complicated processing steps other

Action method as specified in XML format in response to:

[HttpGet("getstudent/{id}")]
[Produces("application/xml")]
public Student GetStudent(int id)
{
    var obj = new Student
    {
        Age = 12,
        Name = "123123"
    };
    return obj;
}

The direct return is as follows:

 XML request

 XML format data request using [Consumes]

 The following code:

The following example XML format request, the program will automatically parse and bind Student model class, this object returns json format (default format returned WebAPI)

[HttpPost("poststudent")]
[Consumes("application/xml")]
public Student PostStudent(Student obj)
{
    return obj;
}

The results are as follows:

 

Guess you like

Origin www.cnblogs.com/qiuguochao/p/11129357.html