No nonsense. Go straight to the topic.
Wcf:
Restful has been popular in recent years. To make ajax calls and support restful Uris, you must manually modify the svc file and specify the Factory after creating an Ajax-enabled Wcf Service:
<% @ ServiceHost Language = "C #" Debug = "true" Service = "ajaxSample. helloWorld "CodeBehind =" HelloWorld. svc. cs "Factory =" System. serviceModel. activation. webServiceHostFactory "%>
NOTE: If no Factory is added, wcf will not be able to directly access it in restful mode similar to http: // localhost/helloWorld. svc/Hello/person/name.
Also remove the <enableWebScript/> in web. config, which is similar:
<System. serviceModel>
<Behaviors>
<EndpointBehaviors>
<Behavior name = "ajaxSample. HelloWorldAspNetAjaxBehavior">
<! -- <EnableWebScript/> -->
</Behavior>
</EndpointBehaviors>
</Behaviors>
<ServiceHostingEnvironment aspNetCompatibilityEnabled = "true"
MultipleSiteBindingsEnabled = "true"/>
<Services>
<Service name = "ajaxSample. HelloWorld">
<Endpoint address = "" behaviorConfiguration = "ajaxSample. HelloWorldAspNetAjaxBehavior"
Binding = "webHttpBinding" contract = "ajaxSample. HelloWorld"/>
</Service>
</Services>
</System. serviceModel>
Now, start to write the code. Since there are two methods of GET/POST in a wcf call, We will write an example method for each of the following common cases:
Copy codeThe Code is as follows:
Using System. Collections. Generic;
Using System. ServiceModel;
Using System. ServiceModel. Activation;
Using System. ServiceModel. Web;
Namespace ajaxSample
{
[ServiceContract (Namespace = "http://yjmyzz.cnblogs.com/")]
[AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode. Allowed)]
Public class HelloWorld
{
/// <Summary>
/// Only Post Restful Methods
/// </Summary>
/// <Param name = "person"> </param>
/// <Param name = "welcome"> </param>
/// <Returns> </returns>
[OperationContract]
[WebInvoke (Method = "POST", UriTemplate = "PostRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat. Json)]
Public List <string> PostRestfulTest (string person, string welcome)
{
List <string> result = new List <string> ();
Result. Add ("PostRestfulTest-> from server :");
Result. Add (person );
Result. Add (welcome );
Return result;
}
/// <Summary>
/// Only Get Restful Methods
/// </Summary>
/// <Param name = "person"> </param>
/// <Param name = "welcome"> </param>
/// <Returns> </returns>
[OperationContract]
[WebInvoke (Method = "GET", UriTemplate = "GETRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat. Json)]
Public List <string> GETRestfulTest (string person, string welcome)
{
List <string> result = new List <string> ();
Result. Add ("GETRestfulTest-> from server :");
Result. Add (person );
Result. Add (welcome );
Return result;
}
/// <Summary>
/// Get and Post Restful Methods
/// </Summary>
/// <Param name = "person"> </param>
/// <Param name = "welcome"> </param>
/// <Returns> </returns>
[OperationContract]
[WebInvoke (Method = "*", UriTemplate = "RestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat. Json)]
Public List <string> RestfulTest (string person, string welcome)
{
List <string> result = new List <string> ();
Result. Add ("RestfulTest-> from server :");
Result. Add (person );
Result. Add (welcome );
Return result;
}
/// <Summary>
/// Only common Post methods (Note: In Post mode, BodyStyle must be set to WrappedRequest or Wrapped)
/// </Summary>
/// <Param name = "person"> </param>
/// <Param name = "welcome"> </param>
/// <Returns> </returns>
[OperationContract]
[WebInvoke (Method = "POST", ResponseFormat = WebMessageFormat. Json, BodyStyle = WebMessageBodyStyle. WrappedRequest)]
Public List <string> PostTest (string person, string welcome)
{
List <string> result = new List <string> ();
Result. Add ("PostRestfulTest-> from server :");
Result. Add (person );
Result. Add (welcome );
Return result;
}
/// <Summary>
/// Only common Get Methods
/// </Summary>
/// <Param name = "person"> </param>
/// <Param name = "welcome"> </param>
/// <Returns> </returns>
[OperationContract]
[WebInvoke (Method = "GET", ResponseFormat = WebMessageFormat. Json)]
Public List <string> GETTest (string person, string welcome)
{
List <string> result = new List <string> ();
Result. Add ("GETTest-> from server :");
Result. Add (person );
Result. Add (welcome );
Return result;
}
}
}
JQuery call code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
$ (). Ready (function (){
$. Post ("HelloWorld. svc/PostRestfulTest/111/222", function (data ){
Alert ("PostRestfulTest is called successfully, and the returned value is:" + data );
})
$. Get ("HelloWorld. svc/GETRestfulTest/333/444", function (data ){
Alert ("GETRestfulTest is called successfully, and the returned value is:" + data );
})
$. Get ("HelloWorld. svc/RestfulTest/555/666", function (data ){
Alert ("RestfulTest GET method call successful, return value:" + data );
})
$. Post ("HelloWorld. svc/RestfulTest/777/888", function (data ){
Alert ("RestfulTest POST method call successful, return value:" + data );
})
$. Get ("HelloWorld. svc/GETTest", {person: "aaa", welcome: "bbb"}, function (data ){
Alert ("GETTest is called successfully, and the returned value is:" + data );
});
$. Ajax ({
Url: "HelloWorld. svc/PostTest ",
Type: "POST ",
ContentType: "application/json ",
Data: '{"person": "ccc", "welcome": "ddd "}',
DataType: "html ",
Success: function (data) {alert ("PostTest call successful, return value:" + data );}
});
})
</Script>
Sometimes, some sensitive information may be required as a parameter (such as the user name/user ID) in the method exposed by WCF. In this case, if you directly use js to call wcf, this part of information may be leaked on the client. In this scenario, we often use the server-side ashx for data transfer.
TestService. svc
Copy codeThe Code is as follows:
Using System. ServiceModel;
Namespace ashx_jQuery
{
[ServiceContract]
Public class TestService
{
/// <Summary>
/// Obtain the salary of the current user for the specified month
/// </Summary>
/// <Param name = "userId"> </param>
/// <Param name = "month"> </param>
/// <Returns> </returns>
[OperationContract]
Public double GetSalary (int userId, int month)
{
If (month = 1) // just for demonstration
{
Return 5000;
}
Else
{
Return 1000;
}
}
}
}
AjaxProcess. ashx
Copy codeThe Code is as follows:
Using System. Web;
Namespace ashx_jQuery
{
/// <Summary>
/// Summary description for AjaxProcess
/// </Summary>
Public class AjaxProcess: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
String month = context. Request ["month"];
TestService wcf = new TestService ();
Double salary = wcf. GetSalary (GetUserId (), int. Parse (month ));
Context. Response. Write ("{salary:" + salary + "}");
}
/// <Summary>
/// Obtain the current user ID
/// </Summary>
/// <Returns> </returns>
Private int GetUserId ()
{
Return 1;
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}
JQuery call:
Copy codeThe Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "default. aspx. cs" Inherits = "ashx_jQuery. _ default" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> jQuery ashx Sample </title>
<Script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"> </script>
<Script type = "text/javascript">
$ (). Ready (function (){
$ ("# BtnTest"). click (function (){
$. Post (
"AjaxProcess. ashx ",
{Month: 1 },
Function (e ){
Var d = eval ("(" + e + ")");
Alert (d. salary );
}, "Html ");
})
})
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Input type = "button" value = "GetSalary" id = "btnTest"/>
</Form>
</Body>
</Html>
Sample Code:Click to download