I'm kinda new to building web applications. I used the template for a ASP.NET Core Web App (Modell-View-Controller) to create a Web Api for REST POST requests.
It was chosen becuase I want to run it on a respberry pi 4 in the end and was able to select the target system when publishing in the Developer PowerShell in VS19.
I currently have a working POST function for request with the Content-Type application/xml. I have to adjust the server POST function because the request is not changeable.
I used an additional service to be able to work with xmls:
services.AddMvc(config =>
{
config.InputFormatters.Insert(0, new XDocumentInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Latest).AddXmlSerializerFormatters();
The used POST method:
[HttpPost]
[Consumes("application/xml")]
public void PostApplXML([FromBody] XDocument value)
{
}
I did send my request with Fiddler and received all the data I needed. I also checked it in VS and analyzed the received data.
I have an issue regarding a second POST function for Content-Type text/xml;charset=utf-8. I tried various input parameters to be able to receive the data but was not able to see them in my function.
These are the different ways I have already tried with the responses from Fiddler:
[HttpPost]
[Consumes("text/xml")]
public void PostTextXML(HttpRequestMessage request)
{
//Fiddler: HTTP/1.1 415 Unsupported Media Type
}
[HttpPost]
[Consumes("text/xml")]
public void PostTextXML([FromBody] HttpRequestMessage request)
{
//Fiddler: HTTP/1.1 415 Unsupported Media Type
}
[HttpPost]
[Consumes("text/xml")]
public void PostTextXML(string request)
{
//Fiddler: Status OK, request = NULL
}
[HttpPost]
[Consumes("text/xml")]
public void PostTextXML([FromBody] string request)
{
//Fiddler: HTTP/1.1 500 Internal Server Error
}
Edit:
I forgot to mention that I also added an InputFormatter especially for the xml data in the Startup.cs:
public class XDocumentInputFormatter : InputFormatter, IInputFormatter, IApiRequestFormatMetadataProvider
{
public XDocumentInputFormatter()
{
SupportedMediaTypes.Add("application/xml");
}
protected override bool CanReadType(Type type)
{
if (type.IsAssignableFrom(typeof(XDocument))) return true;
return base.CanReadType(type);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var xmlDoc = await XDocument.LoadAsync(context.HttpContext.Request.Body, LoadOptions.None, CancellationToken.None);
return InputFormatterResult.Success(xmlDoc);
}
}