The Challenge of Cross-Origin Resource Sharing in WebAPI

I'm working on a basic webapi project with default controllers. I need to access the same values from an HTML page using an ajax request.

Key Points:

  1. Retrieve the token using the token method
  2. Pass the token to get the values

Client-Side:

Below is my HTML page with two buttons. The first button is used to get the token, and then I manually update the header to fetch the values using the second button.

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // Code for token request
            // Code for data request
        });
    </script>
</head>
<body>
    <button id="btnToken" name="btnToken">Get Token</button>
    <button id="btnData" name="btnData">Get Data</button>
</html>

Server-Side:

I have enabled CORS in the code and have the following in my API configuration:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Configuration settings
    }
}

I also added a preflight request in Global.asax as shown below:

    protected void Application_BeginRequest()
    {
        // Code for preflight request
    }

However, when checking in Chrome, I encountered the following error in the console:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

In IE, the error appears as:

Origin file: not found in Access-Control-Allow-Origin header.

Not sure what I might have done wrong here. Any guidance would be appreciated.

Answer №1

Make sure to provide your EnableCostAttribute instance as an argument to your EnableCors method:

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors); // <----

Answer №2

To get started, locate the file named App_Start/WebApiConfig.cs and insert the provided code snippet within the WebApiConfig.Register method.

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New addition
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Afterward, remember to apply the [EnableCors] attribute to the TestController class:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not included in this snippet...
    }
}

If you are using OAuthAuthorizationServerProvider, consider incorporating the following approach:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        }
    }

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

Encountering an issue in next.js with dynamic routes: getting a TypeError because the property 'id' of 'router.query' cannot be destructured since it is undefined

I am working on creating a dynamic page in next.js based on the ID. Here is the basic structure of my project: File path: app/shop/[id]/page.tsx This is the code snippet: "use client" .... import { useEffect, useState } from 'react' ...

Exploring Twig variables in Node.js with the node-twig package

Despite following the documentation meticulously, and experimenting with various methods, I am still unable to achieve success. I have attempted using the code snippet below, trying to reference the variable in the main file like this: // None of the opti ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

Ways to categorize by a particular date

const vehicleDetails = [ { "record_id": "2ff8212f-5ec9-4453-b1f3-91840a3fb152", "status_date_activity": { "On Rent": 1662021991000 } }, { "record_id": "c8c1 ...

Looking to introduce Vue.js into an established SSR website?

Can Vue be used to create components that can be instantiated onto custom tags rendered by a PHP application, similar to "custom elements light"? While mounting the Vue instance onto the page root element seems to work, it appears that Vue uses the entire ...

Increase the quantity with animation

I am attempting to increment a number within an element on the page. However, I require the number to have a comma included while the increment should only increase by 1 digit every second. The code is currently functional, but I am facing a dilemma regar ...

Understanding the concept of event bubbling through the use of querySelector

I am currently working on implementing an event listener that filters out specific clicks within a container. For instance, in the code snippet below I am filtering out clicks on elements with the class UL.head. <div> <ul class="head"> < ...

Is it possible to dynamically load JavaScript?

I'm currently working on a project that requires me to dynamically add JavaScript. I have a global.js file that contains all the global variables I need to add dynamically. However, I'm facing an issue where global.js is not being added before ut ...

What methods can I use to insert an array of objects into a Query?

I'm currently trying to understand how I can pass an array of objects into my GraphQL query. The documentation seems a bit confusing on this matter. In my project, I am using Apollo on the frontend, Graphql-yoga on the backend, and Prisma as my databa ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...

Create a multidimensional array from an array of objects

I am trying to organize my data by creating an array and listing each material based on its status. Here is the structure of my current array: let data = [ { Name: 'House 1', Details:[ {Materials: ...

PHP Bootstrap Confirmation Dialog Tutorial

Is there a way to implement a delete confirmation dialog? When 'yes' is clicked, the message should be deleted, and when 'no' is clicked, the delete operation should be canceled. At present, this is how it looks in my view: <a href ...

Display or conceal a division underneath a dropdown menu based on selections retrieved from a SQL Server database

Presented here is my JavaScript code. function appendItemforPurchaseOrder() { debugger var rowNumber = parseInt($(".itemmapContainer").attr("data-rownumber")); rowNumber = isNaN(rowNumber) ? 1 : rowNumber + 1; var addNewItemDetailHtml = ...

Display a text field when the onclick event is triggered within a for

Control Panel for($i = 1; $i <= $quantity; $i++){ $data .= '<b style="margin-left:10px;">User ' . $i . '</b>'; $data .= '<div class="form-group" style="padding-top:10px;">'; $data .= ' ...

Tips for properly formatting functional Vue components?

Below is a functional component that functions as intended. <template functional> <div> <input /> </div> </template> <script> export default { name: "FunctionalComponent" } </script> <styl ...

The button functionality gets hindered within the Bootstrap well

I'm trying to figure out what's wrong with my code. Here is the code: https://jsfiddle.net/8rhscamn/ <div class="well"> <div class="row text-center"> <div class="col-sm-1">& ...

React component performing AJAX requests

I have a React component that utilizes highcharts-react to display a chart fetched from an API using some of its state properties. export default class CandlestickChart extends React.Component { constructor (props) { super(props); this ...

initiate a POST request using fetch(), where the data sent becomes the key of

Encountered an issue with sending a POST fetch request where the JSON String turns into the Object Key on the receiving end, specifically when using the { "Content-Type": "application/x-www-form-urlencoded" } header. I attempted to use CircularJSON to res ...

The HTML code may fade away, but the JavaScript is still up and running behind the

Switching between different div elements in my HTML document is a challenge. Here's the code I currently have: <div id="screen1" class="current"> <div id="press_any_key_to_continue"> <font style="font-family: verdana" color="yellow ...

Using TypeScript, you can replace multiple values within a string

Question : var str = "I have a <animal>, a <flower>, and a <car>."; In the above string, I want to replace the placeholders with Tiger, Rose, and BMW. <animal> , <flower> and <car> Please advise on the best approach ...