Cross-Origin Resource Sharing

Discussion in 'ASP.NET WebServices' started by smcneese, Oct 20, 2011.

  1. I have been using web services hosted at DASP for years. I have written some new web services that return JSON that need to be called from Javascript. For develpoment at testing purposes, these new web services need to be called from Javascript residing on another domain. When I try to do this, I get the following error:

    Code:
    XMLHttpRequest cannot load http://www.domain.com/Mobile/service.asmx. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
    As you can see the web services are intalled in a folder under the hosted root and that folder is an Application Folder. I have added the following to the web.config in the Mobile folder but it has no affect:

    HTML:
      <system.webServer>
        <httpProtocol>
          <customerHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
          </customerHeaders>
        </httpProtocol>
      </system.webServer>
    
    Based on what I have read, this should open it up to allow javascript loaded and initiated from any domain access to this service.

    Anyone have any thoughts on this?

    Thank you,

    Steve
     
  2. For Firefox and Chrome support, you can use the following jquery syntax:

    $.support.cors = true;
    $.ajax(...

    For IE support, either use JSONP or a server-side proxy page. I used the proxy page myself with much success. It's an extra hop, but works fine. Basically I created an aspx page in the same domain as the page(s) making the jquery calls. In the code-behind of the aspx page (or in the controller if using MVC), I used WebClient (in System.Net) to call the web service:

    protected void Page_Load(object sender, EventArgs e) {
    var serviceUrl = ConfigHelper.WebServiceBase + Request.QueryString["svc"];
    String[] queryKeys = Request.QueryString.AllKeys;
    int queryCount = Request.QueryString.Count;
    string toHash = "?";
    for (int m = 0; m < queryCount; m++) {
    if (queryKeys[m] != "svc") {
    toHash += queryKeys[m] + "=" + Server.HtmlEncode(Request.QueryString[queryKeys[m]]);
    toHash += (m == (queryCount - 1)) ? "" : "&";
    }
    }
    MakeCall(serviceUrl + toHash);
    }

    private void MakeCall(string url) {
    using (WebClient client = new WebClient()) {
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadCallback);
    client.DownloadStringAsync(new Uri(url));
    }
    }
    private void loadCallback(object sender, DownloadStringCompletedEventArgs e) {
    var response = string.Empty;
    Response.ContentType = "application/json;charset=utf-8";
    if (!e.Cancelled) {
    if (e.Error == null) {
    response = (string)e.Result;
    } else {
    var err = "HTTP/1.1 500 ";
    if (e.Error.Message != null) {
    err += e.Error.Message;
    }
    if (e.Error.InnerException != null) {
    err += " : " + e.Error.InnerException.Message;
    }
    response = err;
    }
    }
    Response.Write(response);
    }

    javascript:

    var proxyAjaxCall = function (serviceName, serviceMethod, json, successCallback, errorCallback, onBeforeSend, onComplete) {
    var _data = decodeURIComponent($.param(json));
    $.support.cors = true;
    var options = {
    cache: false,
    type: "GET",
    url: baseUrl + '_ServiceProxy.aspx?svc=' + serviceName + '/' + serviceMethod + "&" + _data,
    contentType: jsonContentType,
    dataType: 'json',
    success: successCallback
    };
    if (errorCallback != null && errorCallback != undefined) {
    $.extend(options, { error: errorCallback });
    }
    if (onBeforeSend != null && onBeforeSend != undefined) {
    $.extend(options, { beforeSend: onBeforeSend });
    }
    if (onComplete != null && onComplete != undefined) {
    $.extend(options, { complete: onComplete });
    }
    $.ajax(options);
    };
    if ($.browser.msie) {
    proxyAjaxCall('MyWCFService', 'insert', { 'data': data },
    function (data, status) { doSomethingO; },
    throwError(),
    function (jqXHR, settings) { beforeSendMethodCall(); },
    function (jqXHR, settings) { onCompleteMethodCall(); }
    );
    } else {
    $.support.cors = true;
    $.ajax({ ... etc. ...
    });
    }


    ... Hope this helps!
     
  3. Thanks Tim. That was very helpful.
     

Share This Page