webapi wcf rest 跨域问题

如何解决跨域的两种方法,一种是JSONP,一种是 CORS
JSONP的方式就是服务端对返回的值进行回调函数包装,他的优点是支持众多的浏览器, 缺点是仅支持Get的方式对服务端请求。
CORS,他仅需要服务端在返回数据的时候在相应头中加入标识信息。这种方式非常简便。唯一的缺点是需要浏览器的支持,一些较老的浏览器可能不支持CORS特性;

Webservice实现的两种形式,一种是 WCF REST寄宿于WINFORM,另一种是WEBAPI


JSONP实现
$("#btnjsonp2").click(function () {
// wcf rest 跨域访问get jsonp 带参
$.ajax({
url: "http://127.0.0.1:8888/ApiService/GetAccount",//"http://127.0.0.1:8888/ApiService/GetAccount",
type: "get",
beforeSend: function () {
},
dataType: 'jsonp',
data: {
'loginname': 'ghgf',
'password': 'ghgf@htemp'
},
success: function (d) {
alert(d);
},
error: function () {
}
});
});

[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/GetAccount?loginname={loginname}&password={password}")]
string GetAccount(string loginname, string password);

CROS实现
$("#btncors").click(function () {
// wcf rest 跨域访问post cors
$.ajax({
url: "http://127.0.0.1:8888/ApiService/GetName",
type: "post",
crossDomain: true,
beforeSend: function () {
},
dataType: "json",
contentType: 'text/json',
data: JSON.stringify({ "loginname": "张三", "password": "1" }),
success: function (d) {
alert(d);
},
error: function () {
}
});
});

[OperationContract]
[WebInvoke(Method = "POST",// OPTIONS POST
UriTemplate = "GetName",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetName(string loginname, string password);

思路:contentType: 'text/json',服务端接收OPTIONS请求,并添加标识头responseProperty.Headers.Set("Access-Control-Allow-Origin", "*");

地址:

https://pan.baidu.com/s/1Klu69CL5RS78s27NI6JRwA

猜你喜欢

转载自www.cnblogs.com/chen1880/p/12929118.html