No more nonsense, go straight to the subject.
WCF end:
In recent years more popular restful, in order to enable Ajax calls, but also in order to support the RESTful style URI, after creating a ajax-enabled WCF service, you must manually modify the Svc file, specify factory, namely:
<%@ ServiceHost language= "C #" debug= "true" service= "Ajaxsample.helloworld" codebehind= "HelloWorld.svc.cs " factory= "System.ServiceModel.Activation.WebServiceHostFactory" %>
Note: If you do not add factory, WCF will not be able to access it directly in a restful manner similar to http://localhost/helloWorld.svc/Hello/person/name.
Also remove the <enablewebscript/> in web.config, which is similar to the following:
<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>
OK, start writing code, given the two ways that WCF calls are Get/post, here's a sample method for several common scenarios:
Copy Code code 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>
RESTful method with Post only
</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>
RESTful method with only get
</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>
RESTful method of Get and post
</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>
General method for Post only (note: 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>
General method of Get only
</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 Calling Code:
Copy Code code as follows:
<script type= "Text/javascript" >
$ (). Ready (function () {
$.post ("helloworld.svc/postrestfultest/111/222", function (data) {
Alert ("Postrestfultest call succeeded, the return value is:" + data);
})
$.get ("helloworld.svc/getrestfultest/333/444", function (data) {
Alert ("Getrestfultest call succeeded, the return value is:" + data);
})
$.get ("helloworld.svc/restfultest/555/666", function (data) {
Alert ("Restfultest get method call succeeded, the return value is:" + data);
})
$.post ("helloworld.svc/restfultest/777/888", function (data) {
Alert ("Restfultest Post method call succeeded, the return value is:" + data);
})
$.get ("Helloworld.svc/gettest", {person: "AAA", Welcome: "BBB"}, function (data) {
Alert ("Gettest call succeeded, the return 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 succeeded, the return value is:" + data);}
});
})
</script>
Sometimes, WCF exposed methods may need some sensitive information as parameters (such as user name/user ID, etc.), if the direct use of JS to invoke WCF, this part of the information may be leaked in the client, this scenario, we often use a service-side ashx to do the relay
Testservice.svc
Copy Code code as follows:
Using System.ServiceModel;
Namespace Ashx_jquery
{
[ServiceContract]
public class Testservice
{
<summary>
Get wages for the current user-specified month
</summary>
<param name= "UserId" ></param>
<param name= "Month" ></param>
<returns></returns>
[OperationContract]
public double getsalary (int userid,int month)
{
if (month = 1)//Only Demo
{
return 5000;
}
Else
{
return 1000;
}
}
}
}
Ajaxprocess.ashx
Copy Code code 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>
Get the current User ID
</summary>
<returns></returns>
private int GetUserID ()
{
return 1;
}
public bool IsReusable
{
Get
{
return false;
}
}
}
}
jquery Call:
Copy Code code 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 ">
<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>
<body>
<form id= "Form1" runat= "Server" >
<input type= "button" value= "Getsalary" id= "btntest"/>
</form>
</body>
Sample code:
Click to download