You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS2019中VB.NET Web API如何接收POST请求传入的XML数据

VB.NET Web API 读取POST请求XML数据解决方案

控制器实现代码

直接替换你现有控制器的占位代码即可:

Imports System.Net
Imports System.Net.Http
Imports System.Xml
Imports System.Web.Http

Namespace Controllers
    Public Class EmployeesController
        Inherits ApiController

        <HttpPost>
        <Route("api/employees/processxml")> ' 自定义路由,可按需修改
        Public Function ProcessStockXml() As HttpResponseMessage
            ' 对应C#的读取逻辑
            Dim doc As New XmlDocument()
            doc.Load(Request.Content.ReadAsStreamAsync().Result)
            
            ' 示例:读取XML中的stock_code节点值
            Dim stockCode As String = doc.SelectSingleNode("/stock/stock_code")?.InnerText
            
            ' 这里可以调用你之前对接的数据库存储过程做后续处理
            ' .....你的业务逻辑.....
            
            ' 示例返回结果
            Return Request.CreateResponse(HttpStatusCode.OK, New With {
                .status = "success",
                .received_stock_code = stockCode
            })
        End Function
    End Class
End Namespace

调用注意事项

  • 如果使用Web API默认路由规则,不需要加Route特性,直接将方法命名为Post即可,POST请求到/api/employees就会自动触发该方法
  • Postman提交请求时,必须在请求头添加Content-Type: application/xml,否则Web API无法正确识别XML格式的请求体
  • 若需使用模型绑定直接接收XML映射的实体,可先定义对应结构的VB类,然后在方法参数中直接声明该类对象,Web API会自动完成XML反序列化
  • 如需避免Result可能导致的线程死锁问题,可使用异步方法实现,参考代码如下:
<HttpPost>
<Route("api/employees/processxmlasync")>
Public Async Function ProcessStockXmlAsync() As Task(Of HttpResponseMessage)
    Dim doc As New XmlDocument()
    Dim stream = Await Request.Content.ReadAsStreamAsync()
    doc.Load(stream)
    
    ' 后续业务逻辑和同步写法一致
    Dim stockCode As String = doc.SelectSingleNode("/stock/stock_code")?.InnerText
    
    Return Request.CreateResponse(HttpStatusCode.OK, New With {
        .status = "success",
        .received_stock_code = stockCode
    })
End Function

内容的提问来源于stack exchange,提问作者earbasher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:06:03