This article is inspired by the jquery Ajax in xuebinding to call the page background method and Web Service definition method. The original Article described this method for directly calling the Web service method on the ASPX page, it is very lightweight, but the author only gives the Code, some of which are not described in detail. Here I will spend some time to analyze the principles in depth.
First, let's look at the code. Note that this method is located in the aspx code file:
Using system. Web. Services;
/// <Summary>
/// Ajax call without Parameters
/// </Summary>
/// <Returns> </returns>
[Webmethod]
Public static string sayhello (){
Return "Hello Ajax ";
}
Jquery calls this method in JSON mode:
$.ajax({
type: 'post',
url: 'TextAjax.aspx/SayHello,
data: data,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(data) {
alert(data.d);
}
});
The effect is as follows:
Pay attention to the following issues:
1. The webmethod method must be a static method;
2. Ajax requests cannot use the get method.
3. If vs2005 is used, you need to add a reference to system. Web. Extensions (system. Web. Extensions. dll may be required) in the system. Web Section of Web. config:
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
1. Why can aspx implement web services?
In our impression, it seems that the Web Service of Asp.net is. the end of asmx, and our current Asp.net can also implement web services, because the default web. system. web. handlers. scriptmodule, which is an HTTP module used to manage Ajax functions in Asp.net. the asmx file is still. all aspx files use this handler to process requests.
In web. config, you can see the handler for. asmx:
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
In vs2005 (Asp. net2.), the default configuration for. asmx processing is as follows:
<add path="*.asmx" verb="*" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="False"/>
Visible. the asmx processing program consists of system. web. services. protocols. webservicehandlerfactory is changed to system. web. script. services. scripthandlerfactory, view system. web. extensions. the scripthandlerfactory method of DLL:
View code
public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
IHttpHandlerFactory factory;
if (RestHandlerFactory.IsRestRequest(context))
{
factory = this._restHandlerFactory;
}
else
{
factory = this._webServiceHandlerFactory;
}
IHttpHandler originalHandler = factory.GetHandler(context, requestType, url, pathTranslated);
bool flag = originalHandler is IRequiresSessionState;
if (originalHandler is IHttpAsyncHandler)
{
if (flag)
{
return new AsyncHandlerWrapperWithSession(originalHandler, factory);
}
return new AsyncHandlerWrapper(originalHandler, factory);
}
if (flag)
{
return new HandlerWrapperWithSession(originalHandler, factory);
}
return new HandlerWrapper(originalHandler, factory);
}
Scripthandlerfactory adds resthandlerfactory processing while being compatible with webservicehandlerfactory.
2. Why is data. D?
In the js code, you can see that the access to the returned object is data. D. You can also see the returned data in the console as follows:
{"d":"Hello Ajax"}
What is this. D? In fact, it is designed to avoid various cross-site XSS attacks, and the get method is not allowed. For detailed analysis, please refer to the response from the official Asp.net staff.
Extension
This method of calling this page still has many merits, especially the logic is relatively simple. It is especially suitable for methods called only on the current page without the need to encapsulate public methods. Here I encapsulate the code called by the client:
/*
* Basic Ajax request processing class
*/
Function ajaxrequestbuiler (URL, Data, callback ){
VaR async =! (Callback = undefined );
VaR response = $. Ajax ({
Type: 'post ',
URL: URL,
Data: data,
Contenttype: "application/JSON; charset = UTF-8 ",
Datatype: 'json ',
Async: async,
Success: function (data ){
If (!! Callback ){
Complete (data );
}
}
});
If (! Async ){
Try {
Return eval ('+ response. responsetext +'). d;
} Catch (error ){
}
}
Function complete (OBJ ){
Callback (OBJ );
}
}
The synchronous call and asynchronous callback methods are used as follows:
Function requestajax (){
VaR d = ajaxrequestbuiler ('testajax. aspx/sayhello ');
Alert ('synchronous loading without callback: '+ D );
Ajaxrequestbuiler ('testajax. aspx/sayhel', null, function (data ){
Alert ('callback asynchronous loading: '+ data. D );
Alert ('callback successful ');
});
}
Code