我在web应用程序中有WCF服务,在另一个web应用程序上有Ajax客户端。就跨域问题而言,我对GET ajax调用没有问题,但对POST ajax调用有问题。我不确定这是来自跨领域的问题。无论如何,当GETAjax成功调用WCF服务时,但在POST ajax调用的情况下却没有。
WCF服务
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UserService/AddUser", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public User AddUser(User input)
{
var user = input;
// Do something business logic
return user;
}
WCF服务所在的web应用程序中的Global.asax
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
Ajax代码
<script type="text/javascript">
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
cache: false,
type: "POST",
async: false,
url: "http://localhost:2000/UserService/AddUser",
data: { "LoginId" : $("#LoginId").val(), "Name" : $("#Name").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (userViewModel) {
var user = userViewModel;
alert(user);
}
});
});
});
</script>
我在Chrome浏览器中用开发者工具调试了它,我得到了以下消息
Request URL:http://localhost:2000/UserService/AddUser
Request Method:POST
Status Code:400 Bad Request
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:windows-949,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:18
Content-Type:application/json; charset=UTF-8
Host:localhost:2000
Origin:http://localhost:3000
Referer:http://localhost:3000/views/useradd.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7
Request Payload
LoginId=11&Name=22
Response Headersview source
Access-Control-Allow-Origin:*
Cache-Control:no-cache, no-store
Connection:Close
Content-Length:1760
Content-Type:text/html
Date:Tue, 14 Feb 2012 05:56:42 GMT
Expires:-1
Pragma:no-cache
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
正如你所看到的,这是400坏请求,这就是为什么我怀疑这个问题与跨域问题有关。但我不确定。
你能猜出这个问题的原因吗?提前谢谢。
我认为问题是您应该使用另一种格式的消息体,因此您应该为data
参数使用其他值:
data: JSON.stringify({
LoginId: $("#LoginId").val(),
Name : $("#Name").val()
})
请参阅答案,其中包含的数据表示形式的不同格式取决于您使用的BodyStyle
属性。
我猜,这可能仍然是一个跨域问题,因为端口不同。
googlechrome-dev工具可能会提供更多信息,你应该在那里看到response选项卡,响应可能会有一个错误,为什么请求没有得到满足,同样工具的控制台可能会给出更多信息。
尝试在端口80上托管您的服务,因为它解决了跨域问题。
1-确保在webHttpBinding
中设置crossDomainScriptAccessEnabled="true"
配置文件应如下所示
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
2-你的方法应该像下面的一样装饰
获取再请求:
[OperationContract]
[WebGet(UriTemplate = "/Dowork/{name}/{action}", ResponseFormat = WebMessageFormat.Json)]
CompositeType DoWork(string name, string action);
对于邮寄请求:
[WebInvoke(UriTemplate = "/DoworkPOST/{name}", Method = "POST", ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
[OperationContract]
CompositeType DoWorkPost(string name, string action1, string action2);
3在java脚本中,您可以访问如下
//for get
function testGet() {
$.ajax({
url: 'http://www.yourhost.com/yourservicename.svc/DoWorkPost/azadeh1',
success: function (data) {
$("#result").html('Load was performed' + data);
}
});
}
//for post
var testobj = { action1: "cook", action2: "dance" };
function testPost() {
$.ajax({
type: "POST",
url: 'http://www.yourhost.com/yourservicename.svc/DoWorkPost/azadeh',
data: JSON.stringify(testobj),
crossDomain:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: false,
success: function (data) {
$("#result").html('Load was performed' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#result").text(textStatus);
}
});
}
4-检查你的svc文件
<%@ ServiceHost Language="C#" Debug="true" Service="namespace.servicename" CodeBehind="servicename.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>