大神有沒有?看看ajax post 資料到WCF為啥總報405或跨域?
阿新 • • 發佈:2019-02-01
一個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);
}
});
});