0

Please Help!! I began to cry.

I want to create an intranet application with angular and ASP.Net Web API. I can get data from the API, but I can't post string/object to the web Api. I created my WebApi:

I put config.EnableCors() in the WebAPiConfig.cs config.EnableCors()

I created a model class "Idea":

 public class Idea
{
    public string Label { get; set; }
}

I created a controller for "Idea"

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApplication1.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    [RoutePrefix("Api/Idea")]
    public class IdeaController : ApiController
    {

        [HttpGet]
        [Route("getIdeas")]
        public List<Models.Idea> GetIdees()
        {
            List<Models.Idea> List_Ideas = new List<Models.Idea>();



            Models.Idea myIdea = new Models.Idea();

            myIdea.Label = "This works!";

            List_Ideas.Add(myIdea);


            return (List_Ideas);
        }


        [HttpPost]
        [Route("InsertIdeaString")]
        public IHttpActionResult PostIdeaString([FromBody] string Label)
        {

            return Ok(Label);
        }

        [HttpPost]
        [Route("InsertIdeaObject")]
        public IHttpActionResult PostIdeaObject([FromBody] Models.Idea myIdea)
        {

            return Ok(myIdea.Label);
        }

    }
}

In my Angular application, I created a service, a model:

    import { Injectable } from '@angular/core';
    import  { IdeaModel } from '../Model/idea-model';
    import { HttpClient, HttpHeaders, HttpParams  } from '@angular/common/http';
    import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class IdeaServiceService {

  url = 'http://localhost:52133/Api/Idea';  

  constructor(private http: HttpClient) { }


  getIdees(): Observable<IdeaModel[]> {  
    return this.http.get<IdeaModel[]>(this.url + '/getIdeas', { 
      headers:  {}
    });  
  }  



  createIdea_Object(idea: IdeaModel): Observable<void> {  

    const config = new HttpHeaders().set('Content-Type', 'application/json');
    return this.http.post<void>(this.url + '/InsertIdeaObject', JSON.stringify(idea), { headers: config });
  }  


  createIdea_String(idea: string): Observable<void> {  

    const httpOptions = { headers:{ "content-type" : "text/html"} };  
    return this.http.post<void>(this.url + '/InsertIdeaString', idea, httpOptions);  
  }  

}

I created the model:

    export class IdeaModel {
    Label:string;
}

In App.component.html:

<button type="button" class="btn btn-secondary"  (click)="create_from_object()"  >Click create object idea </button>
<button type="button" class="btn btn-secondary"  (click)="create_from_string()"  >Click create string idea </button>

<router-outlet></router-outlet>

And in App.component.ts:

import { Component } from '@angular/core';
import { IdeaModel  } from './Model/idea-model';
import { IdeaServiceService } from  './Service/idea-service.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular';

  constructor(private IdeaServiceService: IdeaServiceService) { }


  ngOnInit() {
    this.IdeaServiceService.getIdees().subscribe(
     (res=> {
        console.log(res);
      })
    );
}




  create_from_object():void
  {
    let myIdea:IdeaModel = new IdeaModel;
    myIdea.Label="this works?!";


    this.IdeaServiceService.createIdea_Object(myIdea).subscribe(
      (res=> {
      console.log(res);
      })
    );
  }





  create_from_string():void
  {

    let myString: string="this works?!";

    this.IdeaServiceService.createIdea_String(myString).subscribe(
      (res=> {
      console.log(res);
      })
    );
  }

}

When I launch the angular, I can get the Idea by the get method: getMethod in browser debug

But, I can't Post a string or an object, when I click on the buttons, I got a bad request:


zone-evergreen.js:2952 OPTIONS http://localhost:52133/Api/Idea/InsertIdeaObject 400 (Bad Request)
scheduleTask @ zone-evergreen.js:2952
scheduleTask @ zone-evergreen.js:378
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:372
scheduleTask @ zone-evergreen.js:211
scheduleMacroTask @ zone-evergreen.js:234
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1107
(anonymous) @ zone-evergreen.js:2985
proto.<computed> @ zone-evergreen.js:1428
(anonymous) @ http.js:2581
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
(anonymous) @ subscribeTo.js:20
subscribeToResult @ subscribeToResult.js:7
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ scalar.js:4
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
create_from_object @ app.component.ts:34
eval @ AppComponent.html:1
handleEvent @ core.js:43993
callWithDebugContext @ core.js:45632
debugHandleEvent @ core.js:45247
dispatchEvent @ core.js:29804
(anonymous) @ core.js:42925
(anonymous) @ platform-browser.js:2668
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:39680
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
Show 12 more frames
localhost/:1 Access to XMLHttpRequest at 'http://localhost:52133/Api/Idea/InsertIdeaObject' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:52133/Api/Idea/InsertIdeaObject", ok: false, …}
OPTIONS http://localhost:52133/Api/Idea/InsertIdeaString 400 (Bad Request)
scheduleTask @ zone-evergreen.js:2952
scheduleTask @ zone-evergreen.js:378
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:372
scheduleTask @ zone-evergreen.js:211
scheduleMacroTask @ zone-evergreen.js:234
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1107
(anonymous) @ zone-evergreen.js:2985
proto.<computed> @ zone-evergreen.js:1428
(anonymous) @ http.js:2581
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
(anonymous) @ subscribeTo.js:20
subscribeToResult @ subscribeToResult.js:7
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ scalar.js:4
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
create_from_string @ app.component.ts:50
eval @ AppComponent.html:2
handleEvent @ core.js:43993
callWithDebugContext @ core.js:45632
debugHandleEvent @ core.js:45247
dispatchEvent @ core.js:29804
(anonymous) @ core.js:42925
(anonymous) @ platform-browser.js:2668
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:39680
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
Show 12 more frames
localhost/:1 Access to XMLHttpRequest at 'http://localhost:52133/Api/Idea/InsertIdeaString' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I tested a lot of codes, and with application/x-www-form-urlencoded in the content Type, I get "null" value for both. And I I put a debug stop point

Insert string Insert Object

Thanks a lot for your help!

1 Answer 1

0

In your:

export class IdeaModel {
    Label:string;
}

try changing the property name to 'label' (no capital L). This is the default way WebApi expects to receive (and send) data.
The requests and responses should be the camelCased version of the C# properties.

This is, of course, if you don't intentionally change it.

Also, in a POST action you don't need the [FromBody] attribute. It expects the data to come from the body of the request.

Good luck :)

Sign up to request clarification or add additional context in comments.

Comments

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.