Throwing SoapException in .Net web service

自闭症网瘾萝莉.ら 提交于 2019-12-01 06:29:50

Your code should work and give you a formatted fault as per the MSDN example or, if you want a result as in the response sample you posted, then a service like this should do the trick:

Imports System
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Xml.Serialization
Imports System.Xml

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class Service1
    Inherits WebService

    <WebMethod()>
    Public Sub Process()
        Dim detailsNode As XmlNode = Nothing
        Dim actorString As String = Nothing
        Throw New SoapException("BlahBlahBlahBlahBlah", SoapException.ServerFaultCode, actorString, detailsNode)
    End Sub
End Class

A call like this:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:Process/>
   </soapenv:Body>
</soapenv:Envelope>

should return this:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <soap:Fault>
         <faultcode>soap:Server</faultcode>
         <faultstring>BlahBlahBlahBlahBlah</faultstring>
         <detail/>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>

You also need to add this to your Web.config file to remove any stacktrace in your fault string:

<configuration>
    <system.web>
        <customErrors mode="On" />
        ...
    ...     
...

Also, it's usually not necessary to build the SoapException by hand but throw more appropriate exceptions and let ASP.NET wrap it in a SoapFault. See here for more details: Using SOAP faults.

Use SoapUI to call your method and you should get the above result. Make sure you make a POST on the SOAP endpoint e.g. http://localhost:8080/Service1.asmx and not on the URL of the test page when you click "Invoke" e.g. http://localhost:8080/Service1.asmx/Process as that does not return SOAP formatted responses.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!