Establishing the Access-Control-Allow-Origin

I have a basic .NET web service:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    [WebMethod]
    public int Add(int x, int y)
    {
        return x+y;
    }


}

Attempting to call from Java Script:

<html>
<head>
    <title></title>



</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script>
        function ss() {

                var webserUrl = "http://localhost:41026/WebService.asmx";
                var soapRequest =
'<?xml version="1.0" encoding="utf-8"?> \
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \
  <soap:Body> \
    <Add xmlns="http://tempuri.org/"> \
      <x>int</x> \
      <y>int</y> \
    </Add> \
  </soap:Body> \
</soap:Envelope>';
                $.ajax({
                    type: "POST",
                    url: webserUrl,
                    contentType: "text/xml",
                    dataType: "xml",
                    data: soapRequest,
                    success: SuccessOccur,
                    error: ErrorOccur
                });

        };
        function SuccessOccur(data, status, req) {
            if (status == "success")
                alert(req.responseText);
        }
        function ErrorOccur(data, status, req) {
            alert(req.responseText + " " + status);
        }
    </script>
    <form>
    <input type="button" value="Click here" onclick="ss()">
    </form>
</body>
</html>  

Encountered an error:

XMLHttpRequest cannot load http://localhost:41026/WebService.asmx. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

It seems like a CORS issue. Unfortunately, I am unable to find a solution. Where should I fix the problem - in the server, client, or the browser?

UPD: Updated the web.config. Now it looks like this:

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

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

    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
</configuration>

However, now I am getting an Internal Server Error 500:

Remote Address:[::1]:41026
Request URL:http://localhost:41026/WebService.asmx
Request Method:POST
Status Code:500 Internal Server Error
Response Headers
view source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:1749
Content-Type:text/xml; charset=utf-8
Date:Tue, 03 Nov 2015 15:29:32 GMT
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcanNjcmlwdG5vbnNlbnNcV2ViU2l0ZTJcV2ViU2VydmljZS5hc214?=
Request Headers
view source
Accept:application/xml, text/xml, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:337
Content-Type:text/xml
Host:localhost:41026
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Request Payload
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">   <soap:Body>     <Add xmlns="http://tempuri.org/">       <x>int</x>       <y>int</y>     </Add>   </soap:Body> </soap:Envelope>

Answer №1

To enable custom headers in the web.config file, you can do so by adding the following code snippet:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble getting PHP and AJAX FormData to communicate with each other

I'm completely baffled! Ajax doesn't seem to be sending the file to PHP, and I can't figure out why. Can anyone make sense of this? Here is the code snippet: ----- HTML ----- <input id="mmSelectedDoc" name="selectedFiles[]" type="file" ...

Completing a Promise without invoking the 'then' method

As I work on developing a small API for the NPM module Poolio, one common dilemma arises regarding error-first callbacks and promises. The challenge lies in how to cater to both types of asynchronous functions while maintaining consistency in APIs and retu ...

Pass data from a JavaScript array to PHP with AJAX

I have sought assistance both here and on stackoverflow in creating an invitation function. Within an AJAX-based search box, users can invite teams. Upon locating and selecting a team, it is stored in an array. However, I now need to access the data from t ...

Having trouble saving user input from a form to a database using axios, mongodb, and vue?

I am a beginner in working with Vue and I'm currently facing an issue while trying to submit user input data to my MongoDB using axios. Although the data from the database is displayed on the page, I can't seem to get the form input data to succe ...

Having trouble with installing a React app using npx create-react-app my-app?

description needed for image Having trouble creating a react application using npx create-react-app my-app... Encountering errors shown in the image. Attempted npm init but it was unsuccessful. Included node.js and vs code in the path. ...

When a click event triggers, use the .get() method in jQuery to retrieve the content of a page and then update

I am currently facing an issue with a div class="contentBlock", which is acting as the container for updating content. <div class="contentBlock"></div> Unfortunately, the script I have written does not seem to be working properly :c $(docume ...

Exploring the wonders of useState in React/JavaScript - a comprehensive guide

I encountered an issue while attempting to map an API request from a useState hook. The fetch operation functions correctly and returns an array of objects that I then assign to my useState variable. Subsequently, when I try to map over the useState varia ...

Generating duplicate uuidv4 key values within a Sequelize model

Hello, I'm new to TypeScript and Express. I've set up a UUID type attribute but it always returns the same value. 'use strict'; const { v4: uuidv4 } = require('uuid'); const { Model, Sequelize } = require('sequelize&apo ...

Guide to importing multiple controllers using express

For my upcoming full stack project, I am working on various controllers like signup, login, and profile. Instead of manually requiring each controller and adding them to the app using individual lines of code, I am seeking a more efficient solution. I env ...

Tips for managing various errors in an Express API - such as addressing 404, 405, 400, and 500 errors

I am still learning the ropes of node.js and am using the express framework to create a REST API. I am looking to manage multiple errors for my API, specifically handling 404, 405, 400, and 500 errors. While express provides a default error handler, I am u ...

A step-by-step guide on inserting a date into a MongoDB database using data from

I have a JSON file that contains an object with a date. How can I ensure that this date field is correctly inserted as a "date" data type in MongoDB? This needs to be achieved using Node.js. { "name": "Jeff Johnson", "email": "<a href="/cdn-cg ...

The persistent loading animation in AngularMaterial Autocomplete does not come to an end

Exploring AngularJS and AngularMaterial: Currently, I am delving into the world of AngularJS and experimenting with AngularMaterial. To put it to the test, I decided to create a sample based on the code provided in the documentation (check codepen). My ap ...

Retrieving an array of objects from the database utilizing AJAX

I am trying to retrieve comments from a database and display them on my webpage. However, the current code is throwing a syntax error because the PHP file is not returning the JSON file properly. Here is a snippet of my PHP code (just the fetching part, n ...

Possible solution to address the issue: xhr.js:178 encountered a 403 error when attempting to access https://www.googleapis.com/youtube/v3/search?q=Tesla

Encountering this console error: xhr.js:178 GET https://www.googleapis.com/youtube/v3/search?q=river 403 A specific component was designed to utilize the API at a later point: const KEY = "mykeyas23d2sdffa12sasd12dfasdfasdfasdf"; export default ...

Mongoose's hook function is effective in the pre-stage but ineffective in the post-stage

When using Mongoose hooks, I aim to automatically change the status property to false if the outstandingBalance property has a value of zero. Although attempting to achieve this with Mongoose's PRE hook works, it requires re-invoking the request afte ...

What is the best way to manage the 'content' attribute in TSX?

I'm currently developing an application that utilizes schema.org. In the code snippet below, you can see how I've implemented it: <span itemProp="priceCurrency" content="EUR">€</span> According to schema.org do ...

Encountering a problem when trying to submit data on a form in Prisma Nextjs due to an

As I construct an editing feature for objects within my postgres database, I am encountering an issue related to form submission. Specifically, when attempting to update fields defined in the schema, I am receiving an error message: client_fetch_error unde ...

In what scenario would I incorporate an interface in a DTO model?

Recently, while working on my unit tests using the Moq framework, I encountered a scenario where I needed to check if a property on one of my DTOs was set within a method. The original implementation involved returning the DTO from the methods and then se ...

Effortlessly handle submissions in your Spring Ajax controller without the need to refresh the

I have integrated Starbox into my Spring page, and I need to find a way to save the user rating to the database without refreshing the page. How can I set up a Spring controller to handle this value without returning a new view? The goal is for the user&ap ...

Invoking a function within a functional component from a React element

Let's imagine a scenario where we have a Child component that is a functional component and contains a function called a(): export default function child({ ... }) { ... function a() { ... } ... } Now, let's introduce a parent ...