问题
I have seen many places in ASP.Net where web services are implemented with an asmx file. The mark-up is nearly always empty (apart a basic web service tag) and all the code is the "code behind".
Is this mark-up file legacy from an older way of doing things or does it serve some other purpose?
回答1:
Actually, the .asmx file is not a markup file, but a file containing markup. It is perfectly legal to have the full web service implementation inside the .asmx file. To use a code behind file is good practice, but not mandatory.
Try to build this example in one asmx file, it works:
<%@ WebService Language="C#" Class="WebService1" %>
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
Even in this case you need:
- The markup to associate service class with the .asmx file
- The location of the .asmx file within the web application to specify the web service address
Edit: To be more specific on the last points:
Every web service needs an endpoint, which is basically an URI to be called by clients. For WCF web services, you usually configure the endpoints in the web.config. The ASP.NET way to define an endpoint is to place the .asmx file somewhere in the web application folder structure. When the webservice is called via this URI the WebService
attribute inside the .asmx file tells IIS which class contains the actual web service implementation.
来源:https://stackoverflow.com/questions/7149345/why-do-asmx-web-services-have-a-markup-file