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

  • 相关阅读:
    POJ 2104 K-th Number(主席树模板题)
    HDU 6072 Logical Chain(Kosaraju+bitset)
    POJ 2728 Desert King(最优比率生成树 01分数规划)
    HDU 6150 Vertex Cover(构造)
    51nod 1693 水群(神奇的最短路!)
    51nod 1444 破坏道路(最短路)
    51nod 1076 2条不相交的路径(边双连通分量)
    HDU 6156 Palindrome Function
    Cortex-M0(+)内核的处理器架构简介
    [转] 软件开发流程
  • 原文地址:https://www.cnblogs.com/chen1880/p/12929118.html
Copyright © 2011-2022 走看看