Angular 2 Application faces rejection by .NET API due to absence of "Access-Control-Allow-Origin"

How can I specify the content type as application/json format?

I have a POST method that is used to add a customer's contact. I have created a WebAPI with the following code snippet...

[Produces("application/json")]
[Route("api/[controller]")]
public class ContactController : Controller
{
    private readonly DatabaseContext _context;
    public ContactController(DatabaseContext context)
    {
        _context = context;
    } 

    [Route("SaveContact")]
    [HttpPost]
    public bool SaveContact(Contact contact)
    {
        return true;
    }


    [Route("GetContactList")]
    [HttpGet]
    public List<Contact> GetContactList()
    {
        var result = _context.Contact.ToList();
        return result;
    }
}

What I have attempted I have used POSTMAN and Fiddler tool to test whether I can send a body to the API. The results are as follows:

a. Fiddler: able to send the data (as a contact model)
[![enter image description here][1]][1]

b. POSTMAN: able to send the data (as a contact model)    
[![enter image description here][1]][1]

Issue I am facing While attempting to make a POST request through Angular 2, I am unable to send the body to the API. I have tried various methods but nothing seems to work. It is frustrating that the model is not populating in the API. Here are the details of how I am sending the request from Angular 2 to the API.

Below are my two different ways to make a Post Request.

import { Headers, Http, HttpModule, RequestMethod, RequestOptions, Response ,Request } from '@angular/http';
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { _App } from "app/app.global"
import { ResponseContentType } from '@angular/http/src/enums';


    @Injectable()
    export class PostService{

        headers:any;
        requestoptions:any;
        constructor(private _http:Http){

       }
        PostMethod2(URL,Body){
            let url:string;
            url = _App._URL;
            const contact = [];
            contact.push(Body);
            console.log(JSON.stringify(contact));
            url = url + URL;
            this.headers = new Headers();
            this.headers.append('Content-Type', 'application/json');
            this.headers.append("Access-Control-Allow-Origin","*");
            console.log(url);
            console.log(this.headers);
            this.requestoptions = new RequestOptions({
                method: RequestMethod.Post,
                url: url,
                headers: this.headers,
                body: JSON.stringify(contact),
                responseType : ResponseContentType.Json,

            })

            return this._http.request(new Request(this.requestoptions))
                .map((res: Response) => {
                    if (res) {
                        debugger;
                        return [{ status: res.status, json: res.json() }]
                    }
                    debugger;
                });

        }

        PostMethod(URL,Body){
            let url : string;
            const contact = [];
            contact.push(Body);

            url = _App._URL + URL;
            this.headers = new Headers();
            this.headers.append('Content-Type', 'application/json');
            this.headers.append("Access-Control-Allow-Origin","*");
            console.log(JSON.stringify(contact));
            console.log(url);
            console.log(this.headers);

            return this._http.post( url,JSON.stringify(contact),{headers:this.headers})
                .map((res: Response) => {
                    if (res) {
                        debugger;
                        return [{ status: res.status, json: res.json() }]
                    }
                    debugger;
                });

        }
    }

Postmethod()

https://i.sstatic.net/UQf05.png

Postmethod2()

https://i.sstatic.net/0R5ky.png

Response https://i.sstatic.net/Dvnwi.png

Here is a request I made through a jQuery Ajax method where you can see that the content-type has a value of application/json, which I am not getting in Angular 2.

https://i.sstatic.net/VqP4L.png

Answer №1

Implement Cors for your application.

Install the Microsoft.AspNet.WebApi.Cors package

In the App_Start/WebApiConfig file, add the following line to the Register method:

config.EnableCors();

In the FooController file, include the following attribute to enable Cors:

[EnableCors(origins: "*", headers: "*", methods: "*")]

Answer №2

To enable cross-origin resource sharing (CORS), it is recommended to allow all domains by using an asterisk (*) in the policy unless the API should be restricted to specific domains only. Also, there is no need for an additional package to achieve this functionality.

public void ConfigureServices(IServiceCollection services)
{
   var originWhiteList = new[] { ... };
   var methods = new[] { "GET", "PUT", "POST", "DELETE" };
   var headers = new[] { .. };
   services.AddCors(options =>
        {
            options.AddPolicy(
                "MyPolicy",
                builder => builder
                    .WithOrigins(originWhiteList)
                    .WithMethods(methods)
                    .WithHeaders(headers)
                    .AllowCredentials());
        });
   ..... 
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");
    ......
}

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

Is there a way to retrieve the index and specific object that was modified using $watch in Angular?

I am receiving an array of objects from an API that is being updated every 2 seconds. I have a $watch function that is monitoring any changes in this array. I want to be able to identify which elements have changed along with their index, so that I can dyn ...

It appears that the library (@ngx-translate/core) that contains TranslateModule may not be compatible with Angular Ivy, resulting in an error in the Angular application

Encountering an issue after upgrading my Angular app from version 15 to 16 and running npm start. The error message is related to compatibility with Angular Ivy, specifically mentioning @ngx-translate/core. Looking for a newer version of the library or adv ...

Something went wrong: [ERR_UNSUPPORTED_ESM_URL_SCHEME]: The default ESM loader only supports URLs with a scheme of file, data, and node

Every time I attempt to run yarn dev to start a discord bot, I encounter the following error. The bot is built using TypeScript. I have attempted to update the Node.js version using nvm, but to no avail. I even tried using older versions of Node.js, going ...

How can I prevent the installation of my Ionic 2 application on devices that have been rooted or jailbroken?

I am currently working on a project involving an Ionic 2 and Angular 2 application. I need to implement a feature that checks whether the device is rooted (in the case of Android) or jailbroken (in the case of iOS). I have experimented with various packag ...

Using ADAL with ASP.NET MVC and Angular for Seamless Login Experience

Currently, we have an ASP.NET MVC application in place but are looking to incorporate Angular for new frontend functions and gradually transition the entire frontend to Angular. However, at this stage, we are facing a challenge where user logins are only b ...

Should the input field only contain spaces, a validation error will be triggered by the user

I am currently working on an Angular form implementation that allows users to enter their phone numbers. I have integrated a custom directive called appPhoneExtMask for formatting the phone numbers and have also implemented Angular form validation for both ...

Updating the background color of the side menu in Ionic 4

Wanting to customize the background color of the side sliding menu in my ionic 4 project Here is the code I am using: <ion-app> <ion-split-pane> <ion-menu> <ion-header> <ion-toolbar color="medium"> ...

Angular2: Learn how to dynamically create input fields when a button is clicked

My current challenge involves replicating input fields on click of a button. I have a set of input fields where data can be entered, and then I need to add another set of the same fields for additional data. There needs to be a way to remove these replicat ...

Jest: Test fails due to import statement in node_module dependency

Short Version I'm experiencing a crash in my Jest test due to a SyntaxError related to an import statement outside a module. The issue arises from a node_module that uses the import statement. How can I resolve this error? Situation Overview In deve ...

Draggable bar charts in Highcharts allow users to interact with the data by clicking

I'm working on creating a chart that allows for setting values by clicking and dragging. While the dragging functionality is working fine, I've run into an issue with the click event. When I click to set a new value, the draggable feature acts er ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

The most efficient method for receiving real-time updates from the server to the app is through Angular 7

Currently, I am in the process of developing an Angular 7 messages service (user to user) for my website. The approach I have taken involves receiving updates from the server (Yii2 REST API) every 3 minutes using an interval function (see code snippet belo ...

Typescript's spellbinding courses

I'm encountering some issues with Typescript and the "@botstan/Magic" library in nodejs. Before we proceed, please take a look at the "Magic" documentation. Follow these lines: import Magic from "@botstan/magic"; import * as _ from "lodash"; @ ...

Retrieve information from Angular 2 response

In my code, I am working with 1 component and 1 service. Here is the component element : ... constructor(private requestService : RequestService) { } ngOnInit() { this.a = this.requestService.send_request(urlWebAPI); console.log(this.a); } ... ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

Animate exclusive fresh components

Exploring the functionalities of the latest animation API in Angular 2 has presented me with an interesting challenge: Within my parent component, I am utilizing *ngFor to display a series of child components. These child components are connected to a sim ...

Encountering an error when updating Angular 2 dynamic forms: "Expression has been altered"

I'm struggling with creating a dynamic nested form that's quite complex, but I just can't seem to get it functioning properly. Essentially, the end result should look similar to this: Desired outcome mockup The user will need to choose a f ...

Angular 4 not throwing errors when using Array.Filter and find

Having trouble filtering a list using Array.find and filter functions. Here is the function in question: setSupplierDetails(supplierId) { const supplier = this.suppliers.filter(tempSupplier => tempSupplier.id === supplierId)[0]; this.supplierName = ...

Activate function upon closure of window.open

I'm facing an issue where I need to load a URL in window.open that saves some cookies in my browser. After the window.open is closed, I want to access those cookies but I haven't been able to find a way to do it. I've tried the following cod ...

Typescript: maintain object value enforcement while preserving explicit keys

One interesting observation I had is that in the example below, I was successful in extracting explicit keys from the object, but had difficulty enforcing its values: const myCollection = { a: {test: 1}, b: {test: 2}, c: {text: 3} // no error ...