vijay sahu
vijay sahu

Reputation: 815

.NET API Does not accept "Access-Control-Allow-Origin" from Angular 2 App

How to set contenty type as application/json format.

I have one post method which use to add the contact of my customer. I have created one WebAPI, which has the following below code...

[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;
        //var result = _context.Contact.Add(contact);
        //return result == null ? true : false;
    }


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

What I have tried I have tried the with POSTMAN and Fiddler tool to test weather I am able to send body to api or not and below are the result of POSTMAN and Fiddler:

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

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

What Problem I am facing:- When I am trying to make the post request through Angular 2 , I am not able to send the body to API. I have tried all the possibilities and nothing does works for me. This is so frustrating that why the model is not getting populate in api. Below are the details how I am sending the request from Angular 2 to API.

Below are my two different way to make an 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()

enter image description here

Postmethod2()

enter image description here

Response enter image description here

Below is the request that I made through jquery Ajax method and if you have noticed then you will see that contenty-type has value of application/json, which I am not getting in case of angular 2.

enter image description here

Upvotes: 0

Views: 63

Answers (2)

Ahmed
Ahmed

Reputation: 1590

You need to allow cors and my advice to make it * as mentioned in another answer unless you need API to be public and used by any domain. and BTW you don't need an extra package for that

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");
    ......
}

Upvotes: 0

anıl yıldırım
anıl yıldırım

Reputation: 963

use Cors.

Install-Package Microsoft.AspNet.WebApi.Cors

App_Start/WebApiConfig - Register method:

config.EnableCors();

FooController:

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

Upvotes: 1

Related Questions