为什么这种非原始类型转换在webmethod参数中失败?

时间:2019-05-09 22:45:41

标签: vb.net casting webmethod

我创建了一个自定义类“ TestStr”,该类旨在与原始字符串互换:

Public Class TestStr
    Public ReadOnly Property Value As String
    Public Sub New(ByVal s As String)
        Value = s
    End Sub
    Public Shared Widening Operator CType(ByVal s As TestStr) As Long
        Return s.Value
    End Operator
    Public Shared Narrowing Operator CType(ByVal s As String) As TestStr
        Return New TestStr(s)
    End Operator
End Class

在实践中,这在大多数情况下似乎可以正常工作:

Dim x As TestStr = "hey"
Dim y As String = x

但是,当我在Web方法中将TestStr作为参数时,如下所示:

<WebMethod(True), ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Shared Function GetClientUserRecord(ByVal ClientUserId As TestStr) As String

Web方法调用失败,并且在浏览器控制台中出现此错误:

Cannot convert object of type "System.String" to type "my.mamespace.TestStr"
   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)
   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)
   at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)
   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

在类设置中是否有我做错的事情,还是VB.NET不支持?作为参考,我正在使用.NET Framework 4.6。这样做的主要目的是使TestStr的构造函数自动处理null / empty字符串,并修剪用户的输入字符串,因此可以使用参数“ test”来调用webmethod,并且我不需要在每一个方法中都进行手动的字符串修剪。用户输入的webmethod。

1 个答案:

答案 0 :(得分:1)

ASP.NET MVC和显然的Web方法也将使用为自定义类型定义的类型转换器,将输入转换为该类型。

type converterSystem.Uri可能是一个很好的例子。对于TestStr这样的简单包装器,您需要做的甚至更少。