Pass Data To ASP.NET Web Service (ASMX) From Cross-Origin

In this blog, we are going to create a “Hello World” ASP.Net Web Service (ASMX) with parameters, and allow a request from cross-origin.

Let’s see some of the best articles in C# corner about ASP.Net Web Service:

Now, here we implement ASP.Net Web Service from Visual Studio 2017.

We have created an empty ASP.Net Web Application solution and added “demo.asmx” in solution.

Then, added code for “HelloWorld” method with “name” parameter as mention below snippet,

  1. [WebMethod]  
  2. [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
  3. public string HelloWorld(string text) {  
  4.     return "Hello World " + text;  
  5. }  

 We will invoke this web service using HTTP verb. So, we defined “ScriptMethodAttribute” for setting response format JSON.

We need to enable script service to invoke & pass parameters in Web Service from the script as shown in the below screenshot:


Then set demo.asmx as the startup page and run/test this web service on IIS:


Below is the example of “HelloWorld” webservice:


Now, we will create another ASP.NET web application which will have index.html to request “Hello world” web service using jQuery,

  1. $.ajax({  
  2.     type: "POST",  
  3.     url: "http://localhost:50555/Demo.asmx/HelloWorld",  
  4.     data: {  
  5.         'text'' Jayesh'  
  6.     },  
  7.     success: function(data) {  
  8.         console.log(data);  
  9.     },  
  10.     error: function(request, status, error) {  
  11.         console.log(request);  
  12.     }  
  13. });  


We will receive this error message: “No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:11111' is therefore not allowed access.”


To solve the above error we will need to add the following code under configuration node in web.config,

  1. <system.webServer>  
  2.     <httpProtocol>  
  3.         <customHeaders>  
  4.             <add name="Access-Control-Allow-Headers" value="accept, content-type" />  
  5.             <add name="Access-Control-Allow-Origin" value="http://localhost:11111" />  
  6.             <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />  
  7.         </customHeaders>  
  8.     </httpProtocol>  
  9. </system.webServer>  

Now, when we request this web service, it will successfully return and the response of the web service is as below in the console:



We have learned about passing data to ASP.NET Web Service (ASMX) from Cross-Origin.

Thanks for reading the article.