C#写的webservice实现可选参数

临时用c#写一个项目,使用asmx实现webservice。代码如下:

    [WebMethod]
    public void AddGroup(String app_key, String app_secret, String group_name)
    {
        String res = addGroup.add(app_key, app_secret, group_name);
        
        Context.Response.Charset = "UTF-8";
        Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        Context.Response.Write(res);
        Context.Response.End();
    }

需要实现group_name字段参数可以选择是否传入,现在如果不传入group_name的话C#会自动返回参数不全。如下:

System.InvalidOperationException: 缺少参数: finger_print_base64。
   在 System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   在 System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   在 System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
阅读 9.3k
3 个回答

使用方法重载。
需要在类之前添加WebServiceBinding

[WebServiceBinding(ConformsTo = WsiProfiles.None)]

在方法前添加MessageName

[WebMethod(MessageName = "NoFingerPrint")]

保证两个方法的MessageName内容不同即可

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
public class person : System.Web.Services.WebService
{
    [WebMethod(MessageName = "NoFingerPrint")]
    public void AddPerson(String app_key, String app_secret, String group_name, String person_id)
    {

    }

    [WebMethod(MessageName = "OneFingerPrint")]
    public void AddPerson(String app_key, String app_secret, String group_name, String person_id, String finger_print_base64)
    {

    }
}

貌似不传也没啥影响

[WebMethod]
public string test(string a,string b)
{
    return a + b;
}

图片描述

图片描述

[WebMethod]

public void AddGroup(String app_key, String app_secret, String group_name="")
{
    String res = addGroup.add(app_key, app_secret, group_name);
    
    Context.Response.Charset = "UTF-8";
    Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
    Context.Response.Write(res);
    Context.Response.End();
}

给个默认值试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进