我使用 ServiceStack 创建了一个简单的 web 服务,并且使用内置的 FluentValidation 功能设置了一些验证。如果我使用带有无效数据的 JSON 请求访问服务,一切都会按预期返回。在我的单元测试中,我得到一个 WebServiceException 并且我的响应 DTO 的 ResponseStatus 已按预期填写。但是,如果我随后将完全相同的代码切换到使用 Soap12 客户端,则该服务将返回 HTML,并在其末尾添加一些 SOAP。我将生成的 HTML 保存到一个文件并在浏览器中打开它,果然告诉我哪些验证被触发了。HTML 之后的 SOAP 没有填写 ResponseStatus(它设置为 i:nil="true")。使用 SOAP 端点时,这是预期的吗?
AppHost 验证设置:
Plugins.Add(New ValidationFeature())
container.RegisterValidators(GetType(AppHost).Assembly)
请求 DTO:
<DataContract()> _
Public Class Decode
Inherits AbstractRequest
<DataMember()> Public Property StopCode As String
End Class
请求验证器:
Public Class DecodeRequestValidator
Inherits AbstractValidator(Of Decode)
Public Sub New()
RuleFor(Function(req) req.StopCode).Length(3)
End Sub
End Class
响应 DTO:
<DataContract()> _
Public Class DecodeResponse
Implements ServiceStack.ServiceInterface.ServiceModel.IHasResponseStatus
<DataMember()> Public Property StopName As String
<DataMember()> Public Property ResponseStatus As ServiceStack.ServiceInterface.ServiceModel.ResponseStatus Implements ServiceStack.ServiceInterface.ServiceModel.IHasResponseStatus.ResponseStatus
End Class
服务等级:
Public Class DecodeService
Inherits Service
Public Function Any(request As Decode) As Object
Dim response As New DecodeResponse()
response.StopName = "test"
Return response
End Function
End Class
测试:
<Test()> _
Public Sub InvalidLengthStopReturnsFailure()
Dim client = New Soap12ServiceClient("http://127.0.0.1:81/WebService")
' Works perfectly with JsonServiceClient
Try
Dim response = client _
.Send(Of WebServices.DecodeResponse)(New Decode With {.StopCode = "12"})
Assert.Fail("No exception thrown")
Catch ex As WebServiceException
Assert.IsNotNull(ex.ResponseDto) ' <-- FAIL - ex.ResponseDto is null
End Try
End Sub