Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
XML
Dear,

I have create a webservices. I checked it, its getting data from database as JSON format.I'm Using Visual Studio 2010 Professional. I'm using DevExtrem for mobile when i tried that services i got error then they said you need to create a web services as CORS( Cross domain Services)

Here is the WebService1.asmx file code.

    <WebMethod(), ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
    Public Function GetUserDetails() As String
        Dim dt As New DataTable()
        Using con
            Using cmd As New OleDb.OleDbCommand("SELECT * FROM Mst_User", con)
                con.Open()
                Dim da As New OleDb.OleDbDataAdapter(cmd)
                da.Fill(dt)
                Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
                Dim rows As New List(Of Dictionary(Of String, Object))()
                Dim row As Dictionary(Of String, Object)
                For Each dr As DataRow In dt.Rows
                    row = New Dictionary(Of String, Object)()
                    For Each col As DataColumn In dt.Columns
                        row.Add(col.ColumnName, dr(col))
                    Next
                    rows.Add(row)
                Next
                Return serializer.Serialize(rows)
            End Using
        End Using
    End Function

I did in Global.asax file and also in Web.config file.

Here is the Global.asax file.

Imports System.Web.SessionState

Public Class Global_asax
    Inherits System.Web.HttpApplication

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application is started
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session is started
    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires at the beginning of each request
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
        HttpContext.Current.Response.Cache.SetNoStore()
        Call EnableCrossDmainAjaxCall()
    End Sub

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires upon attempting to authenticate the use
    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when an error occurs
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session ends
    End Sub

    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application ends
    End Sub
    Private Sub EnableCrossDmainAjaxCall()
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*")
        If HttpContext.Current.Request.HttpMethod = "OPTIONS" Then
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST")
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept")
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000")
            HttpContext.Current.Response.[End]()
        End If
    End Sub
End Class

and here is web.config file.

<?xml version="1.0"?>
<configuration>
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
    <compilation debug="true"/>
  </system.web>
  <appSettings>
    <add key="Contsr" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Test.mdb;User Id=admin;Password=;" />
    <add key="CrystalImageCleaner-AutoStart" value="true" />
    <add key="CrystalImageCleaner-Sleep" value="60000" />
    <add key="CrystalImageCleaner-Age" value="120000" />
  </appSettings>
  <connectionStrings>
    <add name="Contr" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Test.mdb" providerName="System.Data.OleDb" />
  </connectionStrings>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

Its working perfectly and showing result. but when i access in mobile platform

i got error. Below is the error.

XMLHttpRequest cannot load http://localhost/Iservice/WebService1.asmx/GetUserDetails. The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:52083' is therefore not allowed access.


Here is my mobile code. I uploaded web services in my Local IIS. and i'm checking mobile services in my local machine. Note that Same thing i uploaded in web but getting same error.

Application17.home = function (params) {
    var myDataSource = new DevExpress.data.DataSource({
        load: function (loadOptions) {
            return $.ajax({
                crossDomain: true,
                url: "http://localhost/Iservice/WebService1.asmx/GetUserDetails",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(params)
            });
        }
    });
    var viewModel = {
        mysource: myDataSource
    };

    return viewModel;

};

Please help on this.

Thanks
Basit.
Posted
Comments
Kornfeld Eliyahu Peter 19-Apr-15 3:14am    
Remove 'crossDomain: true,' from your code...
basitsar 19-Apr-15 3:45am    
I removed then also same error.
XMLHttpRequest cannot load http://localhost/Iservice/WebService1.asmx/GetUserDetails. The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:52083' is therefore not allowed access.

1 solution

I got you!!!
You add Access-Control-Allow-Origin twice in your server (not to mention the client too)...
Once form the code:
C#
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*")

And a second time form the config file:
XML
<add name="Access-Control-Allow-Origin" value="*" />

Do it only once!!!
 
Share this answer
 
Comments
basitsar 19-Apr-15 4:24am    
Thanks dear. But when i removed from Global.asax file (means now no use of global.asax file), i kept in web.config file, the i got the error. Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Kornfeld Eliyahu Peter 19-Apr-15 4:32am    
500 hints, that your changes left Global.asax with some error in it...
basitsar 19-Apr-15 5:22am    
i deleted global.asax file from ASP.Net web services after that i checked the web service once again working perfectly then also same error.

Thanks
Basit.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900