简体   繁体   中英

Angular 2 http.post not working with web api

My Web Api Core Controller Method looks like this

public void Post(Sample sample) {
         _sampleService.CreateSample(sample);
    }

Sample POCO looks like this

  public class Sample : BaseEntity
{
    public string BarCode { get; set; }
    public DateTime CreatedAt { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual Status Status { get; set; }
}

on the client side sample object is only sending 2 properties for now and looks like this.

{barcode:"1234"createdAt:"2017-06-07"}

and the http post looks like this

createSample(sample: Sample) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post(AppConstants.createSample, JSON.stringify(sample), { headers: headers })
  .map((res: Response) => res.json());  }

so if i user headers i get No 'Access-Control-Allow-Origin' header is present

if i not use headers i get (Unsupported Media Type)

any idea whats going on here. UPDATE so I followed instructions as in first answer and looks like CORS is not set property but now JSON is not being converted to C# Object 在此处输入图片说明

  1. You need to use headers to tell the API method what you're sending.

  2. You need to enable CORS in your .Net Core app Startup.cs so that your API allows requests coming from another origin (accepts calls from your client app url, basically) - and set CORS to AllowAnyMethod()

You do this with the following code in your ConfigureServices() method:

var corsUrls = new List<string>(){"http://localhost:4200", "https://mylivesite.com"};

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
    builder
      .AllowAnyMethod() //<--this allows preflight headers required for POST
      .AllowAnyHeader() //<--accepts headers 
      .AllowCredentials() //<--lets your app send auth credentials
      .WithOrigins(corsUrls.ToArray()); //<--this is the important line
}));

services.Configure<MvcOptions>(
    options => { options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy")); });

and then finally in your Configure() method:

app.UseCors("CorsPolicy");

Note that the policy name "CorsPolicy" that I've used is just an example, you can call it whatever you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM