Shuzheng
Shuzheng

Reputation: 13840

How to submit valid XML in a POST request body to an ASP.NET Core Web API that consumes XML?

I've installed the Microsoft.AspNetCore.Mvc.Formatters.Xml and set it up as follows in ConfigureServices():

services.AddMvc().AddXmlSerializerFormatters();

Now, I've created a simple Web API as follows:

[HttpPost]
[Consumes("application/json", new string[]{"application/xml"})]
public ActionResult<string> OnPost([FromBody] ZapScan scan)
{
    return scan.ToString();
}

that accepts a ZapScan through model binding:

public class ZapScan
{
    public string Url { get; set; }
    public bool Priority { get; set; }

    public override string ToString()
    {
        return $"url={Url}, priority={Priority}\n";
    }
}

However, whatever XML I send from Postman is rejected, e.g:

<?xml version="1.0" encoding="UTF-8"?>
<zapscan>
    <url>http://www.example.cm</url>
    <priority>false</priority>
</zapscan>

results in:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|f16a42f4-4c8f4678c6f84eb7.","errors":{"":["An error occurred while deserializing input data."]}}

How to properly format XML in a POST request body to a ASP.NET Web API that consumes XML?

Upvotes: 5

Views: 4673

Answers (1)

Owen Pauling
Owen Pauling

Reputation: 11841

Your XML is invalid. You have two opening <zapscan> tags and no closing tag.

<?xml version="1.0" encoding="UTF-8"?>
<zapscan>
    <url>http://www.example.cm</url>
    <priority>false</priority>
<zapscan> <-- this needs to be a closing tag

Additionally you have an issue with casing, as already covered in the comments.

Upvotes: 2

Related Questions