一个WCF测试例子,使用jquery调用方法.。为啥POST就不可以?
代码下载链接
IAjaxServic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;
namespace WcfService1
{
[ServiceContract(Namespace = "www.yycode.net", Name = "MyTestService")]
public interface IAjaxServic
{
[OperationContract]
void DoWork();
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string MyFirstWCFFunction();
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string MySecondWCFFunction(string name);
[OperationContract]
[WebInvoke(UriTemplate = "/aaabbb", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string MySecondWCFFunction2(UserInfo user, string id);
}
}
AjaxService.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[JavascriptCallbackBehavior(UrlParameterName ="jsoncallback")]
public class AjaxService : IAjaxServic
{
// 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
// 要创建返回 XML 的操作,
// 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// 并在操作正文中包括以下行:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
public void DoWork()
{
// 在此处添加操作实现
return;
}
public string MyFirstWCFFunction()
{
return "aaabbb";
}
public string MySecondWCFFunction(string name)
{
string strMsg = string.Format("我的第二个WCF方法~", name);
// 在此处添加操作实现
return strMsg;
}
public string MySecondWCFFunction2(UserInfo user, string id)
{
return "bbb";
string strMsg = string.Format("test post", user.ToString());
// 在此处添加操作实现
return strMsg;
}
// 在此处添加更多操作并使用 [OperationContract] 标记它们
}
}
配置文件web.config与 app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1"/>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
<system.serviceModel>
<diagnostics performanceCounters="Default" />
<bindings>
<webHttpBinding>
<binding name="AjaxServiceBinding" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<services>
<service name="WcfService1.AjaxService">
<endpoint address="" behaviorConfiguration="WcfService1.AjaxServiceAspNetAjaxBehavior"
binding="webHttpBinding" bindingConfiguration="AjaxServiceBinding"
name="AjaxService1" contract="WcfService1.IAjaxServic" />
<host>
<baseAddresses>
<add baseAddress="http://127.0.0.1:17517/AjaxService.svc" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="WcfService1.AjaxServiceAspNetAjaxBehavior">
<webHttp />
<!--<enableWebScript />-->
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
-->
<directoryBrowse enabled="true"/>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
然后HOST到Winform
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WCF_TEST
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ServiceHost m_Host = null;
private void button1_Click(object sender, EventArgs e)
{
try
{
m_Host = new ServiceHost(typeof(WcfService1.AjaxService));
if (m_Host.State != CommunicationState.Opened)
{
m_Host.Open();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
另一项目jQUERY调用
$(document).ready(function () {
$("#Button1").click(function () {
$.ajax({
type: "GET",
url: "http://localhost:17517/AjaxService.svc/MyFirstWCFFunction?jsoncallback=?",
dataType: "json",
data: {},
//contentType: 'application/json; charset=utf-8',
//async: false,//非异步
//crossDomain: true,
success: function (data) {
console.log(data);
},
error: function (str, txtStatus, mes) {
alert(txtStatus + mes);
}
});
});
$("#Button2").click(function () {
$.ajax({
type: "POST",//Post方式
data: { name: '南宫萧尘' },
dataType: "json",
contentType: 'application/json; charset=utf-8',
async: false,//非异步
url: "http://localhost:17517/AjaxService.svc/MySecondWCFFunction?jsoncallback=?",
success: function (data, status) {
console.log(data);
alert(data + status);
},
error: function (str, txtStatus, mes) {
alert(txtStatus + mes);
//alert(mes);
}
});
});
var user1 = { "user": { "name": "Bill", "sex": "Gates" } };
var user2 = { "name": "Bill", "sex": "Gates" };
var users2 = {
"users": [
{ "name": "Bill", "sex": "Gates" },
{ "name": "Thomas", "sex": "Carter" }
]
};
$("#Button3").click(function () {
$.ajax({
//cache: false,
//async: false,
type: "POST",
url: "http://localhost:17517/AjaxService.svc/aaabbb",
data: JSON.stringify(user1),
contentType: 'application/x-www-form-urlencoded',
dataType: "text",
processData: false,
success: function (data, status) {
console.log(data);
alert(data + status);
},
error: function (str, txtStatus, mes) {
alert(txtStatus + mes);
//alert(mes);
}
});
});