开发者

Pass array of parameters to a web method

开发者 https://www.devze.com 2023-03-03 16:47 出处:网络
I would like to pass some parameters to a web method as an array. The web method\'s signature does not have the params keyword.

I would like to pass some parameters to a web method as an array. The web method's signature does not have the params keyword.

I have a variable number of parameters (as the开发者_运维技巧 web method accepts) so I cannot put the array into n single variables.

How can this be done?


params is just syntactic sugar, why not just do something like this:

var myWebService = new MyWebService();
myWebService.MyMethod(new string[] { "one", "two", "three" });

The method signature on the web service side would just be:

public void MyMethod(string[] values);

If you post your web method maybe I can provide a better answer.

EDIT
If you can't modify the web method signature, then I would use an extension method to wrap the difficult to call web service. For example, if our web service proxy class looks like:

public class MyWebService
{
    public bool MyMethod(string a1, string a2, string a3, string a4, string a5,
        string a6, string a7, string a8, string a9, string a10)
    {
        //Do something
        return false;
    }
}

Then you could create an extension method that accepts the string array as params and makes the call to MyWebService.

public static class MyExtensionMethods
{
    public static bool MyMethod(this MyWebService svc, params string[] a)
    {
        //The code below assumes you can pass in null if the parameter
        //is not specified. If you have to pass in string.Empty or something
        //similar then initialize all elements in the p array before doing
        //the CopyTo
        if(a.Length > 10) 
            throw new ArgumentException("Cannot pass more than 10 parameters.");

        var p = new string[10];
        a.CopyTo(p, 0);
        return svc.MyMethod(p[0], p[1], p[2], p[3], p[4], p[5], 
                            p[6], p[7], p[8], p[9]);
    }
}

You could then call your web service using the extension method you created (just be sure to add a using statment for the namespace where you declared you extension method):

var svc = new MyWebService();
svc.MyMethod("this", "is", "a", "test");


Why don't you use..an array?

[WebMethod]
public string Foo(string[] values) 
{
   return string.Join(",", values);
}


Ignore the fact that it is a web method for a moment. Ultimately, it is a method. And like all methods, is either defined to take parameters or not. If it is not defined to take parameters, then you can't pass parameters to it, can you? Not unless you have access to the source code and are able to chance it's definition.

If it is defined to take parameters, then the question is, is it defined to take array parameters or not? If not, then you can't pass parameters to it (not unless you can change it so that it can.)

0

精彩评论

暂无评论...
验证码 换一张
取 消