如何使用重载方法访问Web服务
我正在尝试在Web服务中重载方法但在Visual Studio 2005中尝试“添加Web引用”时遇到System.InvalidOperationException(这是相关的代码片段):
public class FileService : System.Web.Services.WebService { private static readonly MetaData[] EmptyMetaData = new MetaData[0]; public FileService() { // a few innocent lines of constructor code here... } [WebMethod(MessageName = "UploadFileBasic", Description = "Upload a file with no metadata properties")] public string UploadFile(string trimURL , byte[] incomingArray , string fileName , string TrimRecordTypeName) { return UploadFile(trimURL , incomingArray , fileName , TrimRecordTypeName , EmptyMetaData); } [WebMethod(MessageName = "UploadFile", Description = "Upload a file with an array of metadata properties (Name/Value pairs)")] public string UploadFile( string trimURL , byte[] incomingArray , string FileName , string TrimRecordTypeName , MetaData[] metaDataArray) { // body of UploadFile function here
我认为在WebMethod属性上提供不同的MessageName属性将解决此问题,但这是我得到的整个错误消息:
System.String UploadFileBasic(System.String,Byte [],System.String,System.String)和System.String UploadFile(System.String,Byte [],System.String,System.String)都使用消息名称“UploadFileBasic” ”。 使用WebMethod自定义属性的MessageName属性为方法指定唯一的消息名称。
Web服务编译好; 我看不出这里有什么问题。
我的建议是不要使用重载的方法名称。 WSDL中没有这样的概念,为什么还要费心呢?
您需要更改此部分:
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
到这一个:
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
我通常会在Web服务接口后面有一个具有重载方法的类对象,然后在asmx.cs文件中使用不同的名称创建单独的方法。 我知道你可以使用属性,但它只是使更整洁的代码恕我直言。
Web服务不允许操作重载。 但您也可以按照以下步骤操作。
首先你需要改变
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
至
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
其次,对于Overloaded方法,WebMethod的MessageName属性应该是不同的。
namespace foo { /// /// Summary description for TestService /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.None)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class TestService : System.Web.Services.WebService { [WebMethod(MessageName = "HelloWorld1")] public string HelloWorld() { return "Hello World"; } [WebMethod(MessageName = "HelloWorld2")] public string HelloWorld(string Value = "default") { return "Hello World"; } } }
但是如果你要调用URL Like:
http://localhost:15558/TestService.asmx/HelloWorld2?Value=2
它会工作。
但是如果你要调用URL Like:
http://localhost:15558/TestService.asmx/HelloWorld?Value=2
它将显示HTTP 500