admin管理员组

文章数量:1023221

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?

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?

Share Improve this question edited Nov 19, 2024 at 4:51 marc_s 757k184 gold badges1.4k silver badges1.5k bronze badges asked Nov 19, 2024 at 2:35 PatolaPatola 71314 silver badges41 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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

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?

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?

Share Improve this question edited Nov 19, 2024 at 4:51 marc_s 757k184 gold badges1.4k silver badges1.5k bronze badges asked Nov 19, 2024 at 2:35 PatolaPatola 71314 silver badges41 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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

本文标签: Read applicationxml as string from body using ASPNET Core Web APIStack Overflow