WCF AJAX给后台传值跨域问题处理
WCF的跨域处理很蛋疼,因为使用的人少,所以我当时在处理这个问题时候没少花功夫。
首先说一下客户端的服务启动验证代码
using (CACommunicationWebReference.MedExCAServiceClient caService = new CACommunicationWebReference.MedExCAServiceClient())
{
using (OperationContextScope scope = new OperationContextScope(caService.InnerChannel))
{
var httpRequestProperty = new HttpRequestMessageProperty();
//时间加密处理
string timeInfo = AESEncript.Encrypt(DateTime.Now.ToString(), null, null);
httpRequestProperty.Headers[“medEx_Token”] = “medEx_” + timeInfo;
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
msg = caService.CaRunCommand(signType, command, objectJsion);
}
}
上述中CACommunicationWebReference.MedExCAServiceClient是对应的搭建的服务进行引用,当你在用demo进行测试的时候需要添加你搭建的服务引用。httpRequestProperty 来进行处理对应的自定义header属性。此处是我自己加载的一个token的加密处理。这是客户端对服务端的request部分
当初因为找后台对应的请求处理,差点找的崩溃了,还是在偶然间看到了这句话。WebHeaderCollection headerInfo = WebOperationContext.Current.IncomingRequest.Headers;没错,就是它,直接接收到调用当前函数的header请求内容,就这一句话得到所有,后面剩下的都不是问题了。
接下来是AJAX的跨域调用
let sendjson ={
signType:1,
command:0x4013,
objectJsion:‘UserName:用户姓名,DoctorName:用户工号,Mobile:1560221548,DoctorIDCard:152021548522’,
}
console.log(sendjson);
$.ajax({
type: “GET”,
url: “http://127.0.0.1/MedExCAService/Jweb/CaRunCommand?jsoncallback=?”,
contentType: “application/json;charset=utf-8”,
data: sendjson,
dataType: ‘jsonp’,
//跨域请求
xhrFields: { withCredentials: true },
//跨域请求
crossDomain: true,
beforeSend: function (hr) {
//自定义的Header,后台Cors文件要添加配置才可以读取
hr.setRequestHeader(“medex_token”, “chenxizhang”);
},
contentType: “application/json; charset=utf-8”,
// beforesend: function (xhr) {
// xhr.setRequestHeader("medex_token", "chenxizhang");
// console.log(request);
// },
success: function (data) {
console.log(data);
},
此处需要注意几部分:添加对应的跨域请求属性,对应的dataType: ‘jsonp’,时服务后面要加jsoncallback=?",这是jsonp的一种格式处理。
ajax的调用后台跨域其实网上说那么多什么配置文件属性加载,都扯淡,真正的也就是一句话,本人亲测。代码如下:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[JavascriptCallbackBehavior(UrlParameterName = “jsoncallback”)]
public class CAService : ICAService
在你接口的实现上面加上[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)],想知道为什么,自己百度去,这意思就是允许进行跨域访问,是AspNet自己集成的一种访问规则。
[ServiceContract(Name = “CAService”, Namespace = “www.valorcomm.com”)]
public interface ICAService
{
///
/// CA认证RUNCMD方法传参
///
///
///
/// ]
[OperationContract]
[WebInvoke(Method = “GET”, BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string CaRunCommand(int signType, int command, string objectJsion);
当然此处的ServiceContract和OperationContract的属性不能少,对应的WebInvoke和ajax的Method 保持一致,ServiceContract的name值部分,其实可以省略,看自己是否需要,进行处理。