且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从ASPNET中的请求正文中读取原始XML

更新时间:2022-05-31 06:01:03

首先,ASP.NET Core默认不支持XML序列化/反序列化.您必须明确启用:

First, ASP.NET Core does not support XML serialization/deserialization by default. You must explicitly enable that:

services.AddControllersWithViews().AddXmlSerializerFormatters();

然后,要将原始XML格式数据发送到API方法,请求的 content-Type 应该为 application/xml ,然后我们将从请求中接收xml内容正文,因此我们应使用 [FromBody] 属性,并应使用 XElement 接收xml内容.请参考以下示例:

Then, to send raw XML format data to API method, the request's content-Type should be application/xml, and we will receive the xml content from the request body, so we should use the [FromBody] attribute, and we should use the XElement to receive the xml content. Please refer to the following sample:

使用以下代码创建Values API:

Create a Values API with the following code:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{  
    // POST api/<ValuesController>
    [HttpPost] 
    [Route("/xml")]
    public string Post([FromBody]XElement xml)
    {
        return "Hello" + xml.ToString();
    }

然后使用Postman调用此API:

Then using Postman to call this API:

此外,您还可以根据XML元素创建模型,然后使用模型类接收xml内容.检查以下示例:

Besides, you could also according to the XML elements to create model, then using model class to receive the xml content. Check the following sample:

XML内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<UserViewModel>
   <Id>1</Id>
   <Name>aa</Name>
</UserViewModel>

创建一个UserViewModel

Create a UserViewModel

public class UserViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

然后,在API控制器中,使用以下方法接收数据:

Then, in the API controller, using the following method to receive data:

    [HttpPost] 
    public string Post([FromBody]UserViewModel user)
    {
        return "Hello" + user.Name.ToString();
    }

使用邮递员进行检查:

[FromForm] 属性将在请求正文中接收Form数据.顾名思义,表单数据用于发送包装在表单内的数据,例如填写表单时输入的详细信息.通过将它们写为 KEY-VALUE 对来发送这些详细信息,其中密钥是名称";您要发送的条目中的一个,它的价值就是它的价值.有关更多详细信息,您可以参考此线程.

The [FromForm] attribute will receive the Form data in the request body. Form data as the name suggests is used to send the data that you are wrapping inside the form like the details you enter when you fill a form. These details are sent by writing them as KEY-VALUE pairs where the key is the "name" of the entry you are sending and value is it’s value. More detail information, you could refer this thread.

由于您正在使用curl发送请求,因此请尝试使用 -H -header 设置请求标头,如下所示:

Since you are using curl to send request, try to use -H or --header to set the request header, like this:

$ curl -k -X POST https://localhost:5001/xml -d '<foo>bar</foo>' -i -H "Content-Type: text/xml" 

$ curl -k -X POST https://localhost:5001/xml -d '<foo>bar</foo>' -i -H "Content-Type:application/xml" 

$ curl -k -X POST https://localhost:5001/xml -d '<foo>bar</foo>' -i --header "Content-Type: text/xml" 

$ curl -k -X POST https://localhost:5001/xml -d '<foo>bar</foo>' -i --header "Content-Type:application/xml"