首页 > 解决方案 > 通过 javascript 中的 ref/out 参数调用 Webmethod

问题描述

这是我的webmethod

[WebMethod]
    public string CheckService(string name, ref string msg)
    {
        return "Hello" + name;
    }

这是我的ajax电话

$(document).ready(function () {
                $.ajax({
                    type: "POST",
                    url: "<%= ResolveUrl("integrator.asmx/CheckService") %>",
                    data: '{name: "zakki",msg:"" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (data1) {
                        console.log('', data1.d);
                    }
                });
            });

它引发了一个错误

Cannot convert object of type 'System.String' to type 'System.String&'

标签: c#asp.netajaxweb-serviceswebforms

解决方案


简短的回答是:您不能对标有属性的方法中的参数使用传递引用(使用ref/out关键字) 。[WebMethod]

这是解释为什么在异常消息中&添加第二种System.String类型的原因,取自此参考

解码此消息来源的关键是位于文本末尾的“&”。这是将参数传递给函数 BYREF(By-Reference)时使用的语法,并在 C-Notation 中用于指示“传递 AddressOf”变量名称。即使您在 C#/VB.NET 中编写了 WebService,Microsoft 也会在将其作为程序集输出时以 C 类型表示法对其进行转换/编译。

因此,使用[WebMethod]属性的方法中的所有参数都必须使用按值传递,通过删除ref关键字:

[WebMethod]
public string CheckService(string name, string msg)
{
    // return string here
}

推荐阅读