0

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 enter image description here

Raas Masood
  • 1,475
  • 3
  • 23
  • 61

1 Answers1

1
  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.

Steve Land
  • 4,852
  • 2
  • 17
  • 36
  • Will try this in couple of minutes – Raas Masood Jun 08 '17 at 22:05
  • This is a mapping problem between your client and server - my guess is that its because your cases dont match and you havent set the following after you call services.AddMvc(...) `mvcBuilder.AddJsonOptions( x => x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());` – Steve Land Jun 08 '17 at 23:40
  • as its mvc core so i tried services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()) but it looks like by just adding [FromBody] in post method it works but only through PostMan from Angular app it still getting null. It works fine if i use dynamic or JObject – Raas Masood Jun 08 '17 at 23:50
  • Possibly data type related then. The conversion from partial JSON object to your POCO might be invalid - try making a simpler class (string type properties are simplest to start with) and use that - if it works, then change one property type at a time until it stops working - then you know where the problem is. – Steve Land Jun 09 '17 at 00:10
  • So the problem is that if my typescript object contains date it becomes null on server side. For example of i have datetimr propery in POCO and createdAt: Date in my typescript object , it doesn't work – Raas Masood Jun 09 '17 at 00:35
  • Here's how to fix that https://stackoverflow.com/questions/11491938/issues-with-date-when-using-json-stringify-and-json-parse – Steve Land Jun 09 '17 at 00:38
  • https://stackoverflow.com/questions/37055311/angular2-how-to-use-javascript-date-object-with-ngmodel-two-way-binding/37055451#37055451 this answer also helped as this was a form . its working now Thankyou very much :) – Raas Masood Jun 09 '17 at 00:54