Reputation: 3563
In my Asp.Net Core application I have controller with method:
[HttpPost]
public async Task<ActionResult<string>> ProcessMessage([FromBody] object message)
{
string response = "";
//...
return response;
}
When I lauch project and put string or JSON - it works, but when I send XML - it don't.
Input string:
"1 2 3"
Input JSON:
{
"value1": "1",
"value2": "2",
"value3": "3"
}
Input XML:
<Values>
<Value1>1</Value1>
<Value2>2</Value2>
<Value3>3</Value3>
</Values>
Here is my Startup class:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Amazing Swagger", Version = "v1" });
});
services.AddMvc(options =>
{
options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
//...
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Api Title");
});
}
//...
}
Upvotes: 0
Views: 707
Reputation: 528
I've been struggling with a somewhat similar issue recently.
First, could you change the following line in your startup.cs
:
builder.Services.AddControllers();
to
builder.Services.AddControllers().AddXmlSerializerFormatters();
Secondly, the API doesn't return detailed information on why it had an error deserializing your XML input. I recommend you try and manually deserialize it, before letting the controller handle it. Therefore you get way more detailed errors, which will greatly improve error troubleshooting. If you have already done that ignore this paragraph ;-)
Besides that, I'm not certain if you want to handle both JSON and XML requests but otherwise, you can add the following under [HttpPost]
[Consumes("application/xml")]
[Produces("application/xml")]
Upvotes: 2