为了避免在Web服务应用程序中在两个不同的URL(即* .asmx?wsdl URL和自定义URL)上使用两个不同的WSDL混淆,您可以编写一个HttpModule来拦截对* .asmx的请求? wsdl URL并返回您的自定义WSDL .
EDIT: 这是一个例子,根据我之前编写的一些代码进行了改编和简化,使得标准的* .asmx?wsdl URL可以使用自定义WSDL .
using System;
using System.IO;
using System.Web;
using System.Web.Services.Configuration;
namespace DemoWebService
{
public class CustomWsdlModule :
IHttpModule
{
public void
Init(HttpApplication application)
{
// hook up to BeginRequest event on application object
application.BeginRequest += new EventHandler(this.onApplicationBeginRequest);
}
public void
Dispose()
{
}
private void
onApplicationBeginRequest(object source, EventArgs ea)
{
HttpApplication application = (HttpApplication)source;
HttpRequest request = application.Request;
HttpResponse response = application.Response;
// check if request is for WSDL file
if ( request.Url.PathAndQuery.EndsWith(".asmx?wsdl", StringComparison.InvariantCultureIgnoreCase) )
{
// if Documentation protocol is not allowed, throw exception
if ( (WebServicesSection.Current.EnabledProtocols & WebServiceProtocols.Documentation) == 0 )
{
throw new System.InvalidOperationException("Request format is unrecognized.");
}
// get path to physical .asmx file
String asmxPath = request.MapPath(request.Url.AbsolutePath);
// build path to .wsdl file; should be same as .asmx file, but with .wsdl extension
String wsdlPath = Path.ChangeExtension(asmxPath, ".wsdl");
// check if WSDL file exists
if ( File.Exists(wsdlPath) )
{
// read WSDL file
using ( StreamReader reader = new StreamReader(wsdlPath) )
{
string wsdlFileContents = reader.ReadToEnd();
// write WSDL to response and end response without normal processing
response.ContentType = "text/xml";
response.Write(wsdlFileContents);
response.End();
}
}
}
}
}
}
此简化代码假定您的自定义WSDL与扩展名为.wsdl的.asmx文件位于同一文件夹中 . 需要通过web.config文件将HttpModule挂钩到您的Web服务应用程序中:
type="DemoWebService.CustomWsdlModule"
name="CustomWsdlModule"/>