How to use cross domain requests using json with disable web security?

698 views Asked by At

I have the below scripts that make a REST / WCF WEBGET call to return a payload. It works perfectly fine when both AppServer and Web Server in the same domain.

UI Javascript:

model.Source = new kendo.data.DataSource({
    serverFiltering: true,
    pageSize: 5,
    type: 'GET',
    transport: {
        serverFiltering: true,
        serverPaging: true,
        serverGrouping: true,
        read: {
            dataType: "json",
            crossDomain: true,
            url: function () {
                $('#ShowLink').hide();
                var searchValue = $('#someBox')[0].value;
                return $("#SearchUrl").val() + '/' + searchValue;
            },
            error: function (e) {
                //some code
            },
            success: function (e) {
                //some code
            },
            complete: function (e) {
                //some code
            }
        }
    },
    schema: {
        parse: function (response) {
            if (response.length == 0) {
                //some code
            }
            return response;
        }
    }
});

Application Server (WCF)

    [WebGet(UriTemplate = "someresourceA/{id}/group/{searchText}",  
    RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json)]
    public IEnumerable<SomeDTO> SearchUrl(string id, string searchText)
    {
        var repository = _repositoryFactory.GetRepository<IRepo>();
        return repository.GetData(searchText, int.Parse(id));
    }

However, when I do Cross Domain Request. I get the below error

XMLHttpRequest cannot load http:///App.Query.Service/SomeService.svc/resource/1/…%5D%5Bfield%5D=displayText&filter%5Bfilters%5D%5B0%5D%5BignoreCase%5D=true. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

In order to fix I have executed the below command on the chrome browser which I displays the results.

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

The data displayed correctly and expected result returned to the browser.

However I do not want this to do in the production environments. Users will have the browser web security enabled. Therefore the above solution would not work.

Can some please point me to the right direction to avoid this or is there an alternative solution?

I have also tried the webServer/web.config option and did not work.

<system.webServer>
<httpProtocol>
      <customHeaders>
               <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Any ideas greatly appreciated.

1

There are 1 answers

0
Ali Tahouri On BEST ANSWER

In your Javascript ajax you need to use "jsonp" for dataType and no need for "crossDomain: true,"

read: {
     dataType: "jsonp",
     url: function () {
           $('#ShowLink').hide();
           var searchValue = $('#someBox')[0].value;
           return $("#SearchUrl").val() + '/' + searchValue;
     }

and the you need to modify the web.config file in your "App.Query.Service" project and add the following headers:

<system.webServer>
  <httpProtocol>
    <customHeaders>      
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
  </system.webServer>

I had this issue and I've tried following solutions as well, but with following solutions I wasn't receiving those headers (allow-origin) included on my ajax Http responses when I monitored them by Fiddler.

1- CORS on WCF implementing: CustomHeaderMessageInspector : IDispatchMessageInspector implementing: EnableCrossOriginResourceSharingBehavior : BehaviorExtensionElement, IEndpointBehavior

based on directions from here : http://enable-cors.org/server_wcf.html

2- implementing Application_BeginRequest() in Global.ascx.cs

Hope it would be useful.