zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    XMLHttpRequest 对象相关
    slideToggle()---单击隐藏/浮现--jQuery--click() 方法
    如何打开无线网卡开关(常见无线网卡开关样式)-----记一次令人脸红的羞耻操作
    之前写的页面导出Excel表格
    word 快捷键 部分
    windows 快捷键 部分
    推荐几款屏幕录制工具(可录制GIF)
    【myeclipse2014-2017】使用相关
    嵌套的JsonObject与JSONArray的取值---JSON中嵌套JSONArray
    图片素材库
  • 原文地址:https://www.cnblogs.com/chen1880/p/12929118.html
Copyright © 2011-2022 走看看