0

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

6
  • You need to read up on CORS. The server needs to add the headers to the responses to satisfy the browser. You do not send these headers from the client (browser) to the server. Commented Jan 15, 2018 at 9:24
  • Access-Control-Allow-Origin header is set by the server. Clients (browsers) have to set Origin header Commented Jan 15, 2018 at 9:25
  • Also did you enabled CORS Middleware in ASP.NET Core? Its not obvious from your code snippets Commented Jan 15, 2018 at 9:29
  • @GünterZöchbauer I have also tried to send the headers from the client side as well.. :( Commented Jan 18, 2018 at 3:53
  • @Tseng I have installed normal cors package not middleware.. bcz I have gone through some Microsoft document seems like it does not required to install.. Commented Jan 18, 2018 at 3:54

2 Answers 2

1

use Cors.

Install-Package Microsoft.AspNet.WebApi.Cors

App_Start/WebApiConfig - Register method:

config.EnableCors();

FooController:

[EnableCors(origins: "*", headers: "*", methods: "*")]
Sign up to request clarification or add additional context in comments.

1 Comment

Question is about ASP.NET Core btw
0

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

1 Comment

Instead of this I have used AllowAnyOrigin() , AllowAnyHeader(), AllowAnyMethod()... means it will accept all type of headers ,origin and methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.