Requesting CORs on Web API version 2.0

After enabling CORs on a Web API, I encountered an issue where GET and POST requests were failing on Chrome. Interestingly, the GET request worked fine on MS Edge, but the POST request threw two error messages in the console:

The request could not be processed by the server due to invalid syntax.

XMLHttpRequest: Network Error 0x80070005, Access is denied.

The POST code consists of a standard Ajax request with cross-domain enabled:

$.ajax({
    type: "POST",
    crossDomain: true,
    url: 'http://localhost:50915/api/addjob',
    data: JSON.stringify(Job),
    contentType: "application/json;charset=utf-8",
    success: function (data, status, xhr) {
        alert("The result is : " + status + ": " + data);
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
});

On the Web API side, I have installed the CORs Nuget package and made the necessary configurations to enable it:

WebApiConfig.cs

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            var JsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
            if (JsonFormatter != null)
                JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

And the Controller:

[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/addjob")]
[EnableCors(origins: "http://localhost", headers: "*", methods: "*")]
public void AddJob([FromBody] Job job)
{
    using (_tmsPortalDb)
    {
        _tmsPortalDb.Jobs.Add(job);
        _tmsPortalDb.SaveChanges();
    }
}

Both URLs are localhost but on different ports, and they are part of the same VS Solution as separate projects. I believed that enabling CORs for localhost debugging should resolve the issue. Is there something that I might have overlooked?

Answer №1

Here is a suggestion for IIS hosting:

     config.EnableCors(new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true });

For OWIN hosting, you can use the following configuration in your Angular app with WebAPI:

 public class Startup {

    public void Configuration(IAppBuilder app) {

        AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;

        JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

        var config = new HttpConfiguration();
        app.UseCors(CorsOptions.AllowAll);

        //Middleware for security. This will introspect the incoming reference token
        IdentityServerBearerTokenAuthenticationOptions _options = new IdentityServerBearerTokenAuthenticationOptions {
            Authority = ConfigurationManager.AppSettings["IdentityServerURI"],
            ValidationMode = ValidationMode.ValidationEndpoint,
            RequiredScopes = new[] { "xxxxxadmin" },
            ClientId = "xxxxxadmin",
            ClientSecret = "api-secret",
            EnableValidationResultCache = true,
            ValidationResultCacheDuration =  TimeSpan.FromMinutes(10)                
        };

        app.UseIdentityServerBearerTokenAuthentication(_options);

        //Boots up the application
        Bootstraper.BootUp(config, app);
    }
}

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

The error message "bind is not defined in chat.js on line 89 in React js" appears due to a ReferenceError

Greetings! I am new to working with React JS and have encountered an error in my code while developing a project. The console shows the following message: chat.js:89 Uncaught ReferenceError: bind is not defined(…) I am struggling to identify where I ...

Unexpected behavior with jQuery AJAX Callback function:

When attempting to extract data from the success part of an AJAX call, I implemented a callback function for this purpose. Here is the code snippet: var data2; $(function () { function callback(data) { console.log(data); data2 = JSON.parse(data ...

Encountering no automatic refresh feature in Next.js

Encountering an issue with Next.js where the local host index page doesn't automatically refresh whenever a change is made. To provide some context, I initiated a Next.js application using npx create-next-app --use-npm. After starting the local serve ...

Tips on Enhancing a Fetch Query in Laravel with the Help of Ajax

I am encountering difficulty fetching a list of cities with over 40,000 entries. The main issue is the lack of optimization as my browser becomes unresponsive while loading the city data. Within my Laravel Controller, the code snippet below showcases how I ...

The reason for Ajax displaying two views in a Rails 3.1 application

Upon logging into our Rails 3.1 application, AJAX is utilized to display the input screen below. Follow this link to access the log: <%= link_to 'Log', new_part_out_log_path(@part, :format => :js), :remote => true, :id => 'new_l ...

Can you incorporate personalized icons in ReactJS?

Is there a way to incorporate my personally designed custom icons, available in both SVG and TTF formats, into a React project? I am interested in using these icons in my navigation bar, such as creating a unique home icon for the home button. ...

Having trouble loading Three.js in JavaScript file using npm install?

I am encountering a problem when trying to include Three.js in my JavaScript file without using the HTML script element. The error message I receive is "Uncaught SyntaxError: Cannot use import statement outside a module". Although my Three.js code runs suc ...

The padding on the button inside the v-card is not being applied as expected

I am facing an issue with the following code snippet: <v-card height="200"> <v-card-actions class="mb-0"> <v-btn flat color="orange">Share</v-btn> <v-btn flat color="orange">Explore</v-btn> & ...

Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal. let obj = { doc_id: sessionStorage.getItem('doc_id'), batch_no: sessionStorage.getItem('batch_no') } I attempted to make adjustments by a ...

Is there a way for me to add a clickable link within a tooltip?

In my title, I want to insert a clickable link like 'Link' or 'a'. The title is ready for any string you input. <MaterialSwitch title={CLICKABLE STRING HERE} /> ...

Having trouble with AJAX integration when adding two products to the cart? Looking for a solution to resolve this issue?

In the cart view page, I have noticed that when there is only one product in the cart, I am able to increase and decrease the quantity by clicking on the + and - buttons. However, if I add more than one product to the cart, these buttons do not work for an ...

Ways to restrict input text to a specific set of values

When using an input text form, I need to ensure that users only insert values ranging from 1 to 10. However, my attempts to utilize a mask for customization have resulted in allowing values higher than 10. How can I restrict the input to only be allowed b ...

Incorporate new markers into Google maps without the need to constantly initialize the map

My current goal is to have the user input a latitude and longitude into a text box, and then display a marker on the map for that location without needing to reinitialize the map each time. To start, I have set up my map like this: <script type="text/ ...

Transform jQuery scroll script into vanilla JavaScript

While I am quite familiar with jQuery, I find myself struggling when it comes to using pure JavaScript. Could anyone provide guidance on how I can convert my jQuery code into vanilla JavaScript? Your help is greatly appreciated! Below is the code that I ...

AngularJS can be used to display a webpage

After facing the need to print a given page using AngularJS, I came up with a simple solution as shown below: <div class="modal fade" id="extrait" aria-hidden="true" data-backdrop="false"> <table class="table table-hover table-bordered" i ...

The form submits automatically upon loading the page with empty input fields

I recently created a form on my website located at . Initially, the form functioned correctly and the PHP script executed as expected. However, I am now encountering an issue where every time I load the page, a popup message appears indicating that the for ...

A guide on how to perform a PUT or DELETE operation for Azure Table Storage using Node.js

I've been faced with a challenge in my project where I aim to create basic CRUD functionality for Azure Table Storage. However, I'm encountering difficulties in generating a valid SharedKeyLite signature. While I can successfully generate valid ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

Identifying whether a webpage has integrated Google Analytics

I am working with a node server. I provide a Url in the request and utilize cherio to extract the contents. My current goal is to identify whether the webpage uses Google Analytics. How can I achieve this? request({uri: URL}, function(error, response, bod ...

The Primefaces datatable fails to refresh upon deletion of the final row

My intended function is to remove a row from my primefaces datatable and transfer the deleted entry to another datatable. This process works smoothly for all rows except for the last one. The main issue arises after deleting the final row, as the original ...