我经历了很多帖子,但没有得到任何帮助。我正在尝试使用 jquery ajax 调用我的 WCf,但我总是遇到以下错误。
- 400(错误请求)
- 访问控制允许来源。
我的代码如下:
Web.config[服务]
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="UserDetails1Behavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<!--<bindings>
<webHttpBinding>
<binding name="UserDetailsBinding" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>-->
<bindings>
<wsHttpBinding>
<binding name="wsbind">
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="UserDetails1Behavior" name="UserDetails1.Service1">
<endpoint address=""
binding="wsHttpBinding" contract="UserDetails1.IService1"
/>
<!--<endpoint address="mex" binding="wsHttpBinding" contract="IMetadataExchange"/>-->
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
IService1.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace UserDetails1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract(Name = "UserDetails1.Service1")]
public interface IService1
{
// TODO: Add your service operations here
[OperationContract]
// [WebInvoke(Method = "POST",
//BodyStyle = WebMessageBodyStyle.Wrapped,
//ResponseFormat = WebMessageFormat.Json)]
[WebInvoke(UriTemplate = "GetDataUsingDataContract?composite={composite}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string InsertUserDetail(UserDetails userInfo);
[OperationContract]
// [WebInvoke(Method = "GET",
//BodyStyle = WebMessageBodyStyle.Wrapped,
//ResponseFormat = WebMessageFormat.Json)]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
DataSet SelectUserDetails();
[OperationContract]
// [WebInvoke(Method = "POST",
//BodyStyle = WebMessageBodyStyle.Wrapped,
//ResponseFormat = WebMessageFormat.Json)]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
bool DeleteUserDetails(UserDetails userInfo);
[OperationContract]
// [WebInvoke(Method = "POST",
//BodyStyle = WebMessageBodyStyle.Wrapped,
//ResponseFormat = WebMessageFormat.Json)]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
DataSet UpdateUserDetails(UserDetails userInfo);
[OperationContract]
// [WebInvoke(Method = "POST",
//BodyStyle = WebMessageBodyStyle.Wrapped,
//ResponseFormat = WebMessageFormat.Json)]
[WebInvoke(UriTemplate = "GetDataUsingDataContract?composite={composite}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
void UpdateRegistrationTable(UserDetails userInfo);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class UserDetails
{
int userid;
string username;
string password;
string country;
string email;
[DataMember]
public int UserID
{
get { return userid; }
set { userid = value; }
}
[DataMember]
public string UserName
{
get { return username; }
set { username = value; }
}
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[DataMember]
public string Country
{
get { return country; }
set { country = value; }
}
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
}
}
服务1.svc.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace UserDetails1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
public DataSet SelectUserDetails()
{
SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=registration;User ID=sa; Password=saviant");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from RegistrationTable", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public string InsertUserDetail(UserDetails userInfo)
{
string Message;
SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=registration;User ID=sa; Password=saviant");
con.Open();
SqlCommand cmd = new SqlCommand("insert into RegistrationTable(UserName,Password,Country,Email) values(@UserName,@Password,@Country,@Email)", con);
cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
cmd.Parameters.AddWithValue("@Password", userInfo.Password);
cmd.Parameters.AddWithValue("@Country", userInfo.Country);
cmd.Parameters.AddWithValue("@Email", userInfo.Email);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = userInfo.UserName + " Details inserted successfully";
}
else
{
Message = userInfo.UserName + " Details not inserted successfully";
}
con.Close();
return Message;
}
public void UpdateRegistrationTable(UserDetails userInfo)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User ID=sa;Password=saviant");
con.Open();
SqlCommand cmd = new SqlCommand("update RegistrationTable set UserName=@UserName,Password=@Password,Country=@Country, Email=@Email where UserID=@UserID", con);
cmd.Parameters.AddWithValue("@UserID", userInfo.UserID);
cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
cmd.Parameters.AddWithValue("@Password", userInfo.Password);
cmd.Parameters.AddWithValue("@Country", userInfo.Country);
cmd.Parameters.AddWithValue("@Email", userInfo.Email);
cmd.ExecuteNonQuery();
con.Close();
}
public bool DeleteUserDetails(UserDetails userInfo)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User ID=sa;Password=saviant");
con.Open();
SqlCommand cmd = new SqlCommand("delete from RegistrationTable where UserID=@UserID", con);
cmd.Parameters.AddWithValue("@UserID", userInfo.UserID);
cmd.ExecuteNonQuery();
con.Close();
return true;
}
public DataSet UpdateUserDetails(UserDetails userInfo)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User ID=sa;Password=saviant");
con.Open();
SqlCommand cmd = new SqlCommand("select * from RegistrationTable where UserID=@UserID", con);
cmd.Parameters.AddWithValue("@UserID", userInfo.UserID);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
}
}
web.config(客户端)
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_UserDetails1.Service1" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:50861/Service1.svc" binding="wsHttpBinding"
contract="ServiceReference1.UserDetails1Service1" />
</client>
</system.serviceModel>
</configuration>
客户来电
function CallService() {
debugger;
$.ajax({
//type: Type, //GET or POST or PUT or DELETE verb
//url: Url, // Location of the service
//data: Data, //Data sent to server
//contentType: ContentType, // content type sent to server
//dataType: DataType, //Expected data format from server
//processdata: varProcessData, //True or False
async: true,
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:50861/Service1.svc/SelectUserDetails",
dataType: "json",
crossDomain: true,
// data: '{"teamId":"' + teamId + '", "weekNumber":"' + weekNumber + '"}',
success: function (content) {
debugger;
alert(content);
// DisplayRun(map, content);
},
error: function (msg) {
debugger;
ServiceFailed(msg)// When Service call fails
},
failure: function (msg) {
debugger;
alert("fail" + msg);
}
});
}