I have a simple ASP.NET Core Web API. Request is going to be using the application/xml
media type. However, I want to read it as a string inside the controller and do some check before converting that string to XML. A simple method like this returns an "http 415 - media type not supported" error.
[HttpPost()]
public async Task<IActionResult> UpdateStatus([FromBody] string msg)
{}
I can add AddXmlSerializerFormatters
and get the object I want from the body, but that bypasses some of the error handling. Is there a way to read application/xml
as string?
We usually use StreamReader
to read XML content.
[HttpPost]
[Route("update-status")]
public async Task<IActionResult> UpdateStatus()
{
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
string xmlContent = await reader.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(xmlContent))
{
return BadRequest("Empty XML content");
}
return Ok($"Received XML content: {xmlContent}");
}
}
If you still want to get xml content from [FromBody] string msg
, we can create custom InputFormatter
to implement this feature.
PlainTextInputFormatter.cs
using Microsoft.AspNetCore.Mvc.Formatters;
using System.Text;
using Microsoft.Net.Http.Headers;
namespace WebApplication1
{
public class PlainTextInputFormatter : InputFormatter
{
public PlainTextInputFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/plain"));
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml"));
}
protected override bool CanReadType(Type type)
{
return type == typeof(string);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
using (var reader = new StreamReader(request.Body, Encoding.UTF8))
{
var content = await reader.ReadToEndAsync();
return await InputFormatterResult.SuccessAsync(content);
}
}
}
}
Register it
builder.Services.AddControllers(options =>
{
options.InputFormatters.Insert(0, new PlainTextInputFormatter());
});
Test Code and Test Result