Encountering a Issue with POST Method in AngularJS Calling .NET WebAPI

I am currently facing a challenge with my AngularJS and .NET WebAPI integration. While I can retrieve content or objects successfully through the WebAPI, I am encountering difficulties when attempting to POST data.

When trying to post the content, I receive the following errors:

OPTIONS http://localhost:18130/api/Products XMLHttpRequest cannot load

http://localhost:18130/api/Products. Response for preflight has invalid HTTP status code 405

It's worth noting that when using Fiddler to post, everything works perfectly without any issues.

Below is the AngularJS code snippet I'm utilizing for posting:

var data = { "Title": $scope.title, "Description": $scope.description };

$http.post(
    'http://localhost:18130/api/Products',
     JSON.stringify(data), {
         headers: {
             'Content-Type': 'application/json; charset=UTF-8'
          }
      }).success(function (data) {
          console.log(data);
      });

Could someone kindly point me in the right direction? The WebAPI and AngularJS app reside on separate domains—is this a CORS issue? How can I resolve this problem when performing posts?

Thank you in advance.

Answer №1

When creating your web API project, the template used will determine whether OWIN is used or not. If OWIN is being used (if not, refer to scniro's answer for an alternative starting point):

I encountered a similar issue while posting to my web API from a JavaScript application. To resolve this, I installed Microsoft.Owin.Cors from NuGet and added the following code to my Startup.cs:

    public void Configuration(IAppBuilder app) {
        app.UseCors(new CorsOptions {
            PolicyProvider = new CorsPolicyProvider {
                PolicyResolver = context => {
                    CorsPolicy result = new CorsPolicy {
                        AllowAnyHeader = true,
                        AllowAnyMethod = true,
                        AllowAnyOrigin = true,
                        SupportsCredentials = true
                    };                        
                    return Task.FromResult(result);
                }
            }
        });
    }

This configuration allows all requests. For production, you can restrict requests to specific origins like this:

    public void Configuration(IAppBuilder app) {
        app.UseCors(new CorsOptions {
            PolicyProvider = new CorsPolicyProvider {
                PolicyResolver = context => {
                    CorsPolicy result = new CorsPolicy {
                        AllowAnyHeader = true,
                        AllowAnyMethod = true,
                        AllowAnyOrigin = false,
                        SupportsCredentials = true
                    };
                    result.Origins.Add(ConfigurationManager.AppSettings.Get("YourAllowedUrl"));
                    return Task.FromResult(result);
                }
            }
        });
    }

Hopefully, this solution helps.

Answer №2

@Jordan, I suggest you disable all handlers in the web.config file and then readd them:

<modules>
  <remove name="FormsAuthenticationModule" />
  <remove name="WebDAVModule" />
</modules>
<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

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

Revoking JWT tokens upon user logout

Currently, I am working on developing a MEAN App and encountered an issue regarding the destruction of the token generated by JWT. Initially, I believed that utilizing the logout function would suffice: router.get('/logout', function(req, res) { ...

Refresh the webpage source code for an AJAX request

When using AJAX calls on a page, I have noticed that the page source remains unchanged. This can be problematic if a user performs forward/backward operations in their browser, as the browser will display the original HTML code instead of the updated conte ...

Customize the DOM with tailwind CSS in a Vanilla JavaScript project

I am attempting to hide the "mark as complete" button and replace it with a "completed" button by switching the classes from "hidden" to "completed" and vice versa. However, when I use an event listener to manipulate the DOM with the code provided below, t ...

When the page is refreshed, the JWT token mysteriously disappears from the header. How can this issue be resolved

I am currently using Jwt token based authentication with Angular 7 and node.js. When attempting to send a POST request with a Token to the server, everything works fine initially. However, upon reloading the page, I encounter an error on the server side. ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

Enhancing Javascript Dialog Box with a Touch of Animation

Collaborating with the incredibly talented Mark Eirich has been an amazing experience. We have been working on revamping a JavaScript dialog box together, and Mark has set up something on JSFiddle that will be incredibly beneficial. However, I am seeking a ...

php reload page with included content

I am currently in the process of building a website using php, jquery, Sass, Bootstrap, and more. The setup I have in place involves one main index page that contains all the necessary includes for the header, CSS files, and JavaScript files. Different pa ...

Tips for utilizing jQuery Ajax data action

I've been trying to understand how to effectively utilize the data parameter in a $.Ajax call. However, I am facing confusion regarding the 'action' part within the data call. Is it meant to trigger an action in a controller? If so, how can ...

I keep encountering a TypeError whenever I try to type in my input field in ReactJS. What could be causing this

As I work on developing a Recipe Box application, I have encountered a challenge with the input field for the recipe name during the recipe creation process. Whenever I try to enter text into the input field, the following error message appears: https://i ...

Observing changes to attributes in AngularJS is a useful feature that allows for

I am looking to update the attribute of an element by using its id and have the element respond to this change. After trying to showcase my situation in a plunkr, I encountered issues with even getting ng-click to function properly. My goal is to invoke ...

Using JQuery to append elements and then locate them with the find method does not produce the expected

Hey there, I'm having trouble inserting one DOM element into another. It's something I've done many times before successfully, but for some reason it's not working this time and I can't figure out why. Currently, I am using an Aja ...

Looking for assistance with a JavaScript code snippet

I have encountered an issue while iterating through receipts in the given code snippet. The objective is to fetch the receipt number for each receipt and add it to a JSON object. However, I am facing a problem where the same receipt is appearing in two sep ...

Console not displaying array output

Context: Currently, I'm in the process of developing an application that utilizes AJAX to fetch PHP arrays encoded into JSON format for dynamically constructing tables. However, I've encountered an issue where despite having no compilation errors ...

How can I simultaneously submit both the file and form data from two separate forms on a single page using PHP?

My webpage features a form with a series of questions, each followed by an option to upload files if available. I made sure not to nest forms within each other, instead using a method where the upload form pops up separately. However, I encountered an issu ...

Tips for showing legend symbols within tooltips on Highcharts

I've encountered an issue with Highcharts that I need help with. In my Highcharts chart, I'm trying to transfer the symbol from the legend to the tooltip. I'm tackling this challenge in two scenarios: Lines: I have two series, one with a ...

Another class is overriding the border of the text-box

I'm facing a challenge in customizing the material ui css. Specifically, I want to set the border color of a textbox to red. The issue arises when the bottom border gets overwritten. Upon investigation, I discovered that the culprit is the class MuiIn ...

The web form website utilizing Asp.net encounters an issue - the ASP.NET Ajax client-side framework has failed to load

While browsing a website today that was developed using asp.net webform (.net 4.0) around 2014, I noticed design issues after checking the console for errors. I'm not sure why these errors started appearing suddenly today. It could be due to a faulty ...

Problem encountered when attempting to use 'delete' as a property name

I am currently encountering an issue with a form that deletes a gallery from a database. Previously, the code was functioning properly but after some recent updates such as switching from jquery.interface to jquery-ui, I am now facing difficulties. Wheneve ...

Extracting data from websites by manipulating the Document Object Model with the help of Javascript and Ajax

Currently, I am in search of data for educational purposes from a website. Specifically, the website focuses on statistics in web development. The challenge lies in the fact that this particular site uses Javascript/Ajax to constantly update numbers. I w ...

Condition for user account username

I am developing a user registration system using ASP.net and C#. I need help with setting up a check to see if a username already exists before inserting the record. Can anyone provide guidance on how to achieve this? try { Guid newGuid = Guid.NewGu ...