Angular Post Request Received in Net Core API as Null

Angular POST request received in NET Core Api as Null

I dont know why, but this fixed my issue:

I created a header:

 const header = new HttpHeaders()
.set('Content-type', 'application/json');

Changed the POST function by adding a header and JSON.Stringyfy the object:

 add(model: Model): Observable<Model> {
const body = JSON.stringify(c);
return this.http.post<Model>(this.addUrl, body, { headers: header} );
}

Changed [FromForm] to [FromBody].

Adding JSON.stringify(model) in the parameters of the http.post was not working.

JSON that is working with the CORE Api:

{"name":"test","weight":2,"activityTypeModelId":15}

JSON that is not working with the CORE Api:

{name:"test",weight:2,activityTypeModelId:15}

Without the header I encountered a 415 error from the API.

.Net Core 3.0 Angular application post request parameter is always NULL

There are a few different questions in your post that I'd be happy to tackle for you:

Why doesn't Language get populated in your controller method?

You indicate that the method on your API controller looks like:

public IActionResult Post(Language lan)
{
// logic
return Ok();
}

You don't indicate if you're configuring Endpoints in your setup, so I'll assume not. You should update this with to instead look like the following. This will do two things: 1) The first line will inform ASP.NET Core that this method should match a POST request with the named template and 2) the [FromBody] attribute in the argument tells ASP.NET Core where to populate the value from (your POST body).

[HttpPost("Language")] //Handles a call to /language as you attempt in both your first and second calls from Angular.
public IActionResult Post([FromBody]Language lan)
{
//logic
return Ok();
}
Should you use async and Task<T> in your last controller sample

Unless you're performing asynchronous activities in your //logic comment, there's no reason to decorate the method with async or have it return a Task<IActionResult>. The example above is more than sufficient.

Are you even populating any data to send?

This would be worth a peek at your network request to verify, but unless you're doing some mapping in your Angular component, you're setting the value of the option field to "language.key", but in your call to this.http.post, you pass in lang and subsequently lan which both are not otherwise used in your example code. As such, I can't dig much into what might be going on there, but it could be worth opening your network tools in your browser and confirm that the POST request to your server is actually populating with the intended data from the Angular component.

You might be misunderstanding the TypeScript syntax on the Angular side in your calls to this.http.post

You indicate that you're trying to send data with:

this.http.post<LanguageInterface>("Language", lan).subscribe(result => {
console.log(result);
}, error => console.error(error));

My concern here is merely derived from this second example you give given that you're passing in data from a LanguageInterface, presumably into the lan parameter somehow, but you also reference that at this.http.post<LanguageInterface>. The use of <> on the method is to type the response that you're expecting from the call and is not properly used here. Rather, because your controller methods in ASP.NET Core both simply return an Ok() ActionResult, there's no anticipated type for the response, so this wouldn't make much sense here.

In this case, your first post call from Angular uses the correct syntax:

this.http.post("Language", lang).subscribe(result => {
console.log(result);
}, error => console.error(error));

The result will merely contain the HttpResponse and there's not expected to be a body in the response back to you, much less one that should be typed to anything.

Conclusion

Again, I can't speak to how you're mapping between the form and your call to POST the data, but feel free to provide more of your sample code and notify me in a comment and I'd be happy to review it as well.

Within your Angular component

this.http.post("Language", lang).subscribe(result => {
console.log(result);
}, error => console.error(error));

Your ASP.NET Core controller method

[HttpPost("Language")] //Handles a call to /language as you attempt in both your first and second calls from Angular.
public IActionResult Post([FromBody]Language lan)
{
//logic
return Ok();
}
Why does [HttpPost("Language")] break this?

You didn't originally provide the controller signature in your question, so this wasn't obvious before. Because your [Route] attribute on the controller is set as [Route("[controller]")], it is using an ASP.NET Core convention to use the name of the controller before "Controller" - in your case, your class is "LanguageController", so any request to /Language will wind up pointing here as a valid option.

Since I then suggested a route on [HttpPost("Language")], that further adds to the pattern required to match. If you sent a POST request to localhost:<port>/Language/Language, you'd see it match on the method as expected.

To remedy this then, merely changing the attribute on the method to [HttpPost] and eliminating the template argument will mean that this will match a call to localhost:<port>/Language, assuming this is the only POST method with this signature in the controller.

.NET Core API gets null from Angular POST

I fixed it by making my Id parameter not null, but 0 instead. I guess this makes sense because it isn't nullable on the .NET end. This took me two hours.

Angular + Asp Core 2 http Post data is always null

Looking at your example code, my mind jumps to two options:

  1. Wrong headers. Because you're explicitly setting an empty headers object as the third parameter, it might be that this causes Angular to not add a default HTTP header for the content-type you're sending across (application/json). If you don't tell ASP.NET Core what kind of data your sending, then ASP.NET Core doesn't care about it and doesn't apply model binding. The fix for this one is really easy, simply remove that third parameter in your this.httpClient.post() call.

    this.httpClient.post('/tests/export', params).subscribe(result => {
    console.log(result);
    });

    You can verify that this header it set by checking the network traffic in your web developer toolbar.

  2. Case-sensitivity. In JavaScript (and thus JSON), camel-casing is the standard. Your params object has a TestData and an ExportAndExecute, both pascal-cased. It could be that the model binder is sensitive for case.

Dotnet core web API is getting Null data from angular form

I have miss spelled formControlName

Angular 2 http post null Web Api Core

There is no reason to add JSON.stringify(). Try removing it.

EDIT:

Either remove JSON.stringify() or remove the braces around body data:

this.http.post('http://localhost:10832/api/Account/Register', pedido, options)

Angular will try to serialize already serialized JSON string as an object, if you leave it this way and that's why you're having an issue.

Source code: Link

Angular Post json to .net core web api is null

I'll try to answer all your questions.

string issue received on the API is always null

Passing a JSON to this will always get you a null because you are trying to bind to a primitive data type. To fix this you have two options

Bind to a model ( viewmodel )

When your parameter is a class, asp will bind this class to the json data you passed that's why you were able to get the name data.
Based on your update, you might probably go this route.

More info: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

Now you might be wondering why would you create a class just to be used on your api when the parameter is just a string?! If you want to use just the string in your api then you can do this

Pass the data using FormData

You need to change your api like this

 public IActionResult PostIssues(string issue){..}

You don't need to specify the [FromBody] here.

In your client-side,

 public addIssue(issue) {
const headers = new Headers();
this.authService.getToken().toPromise().then( t => {
headers.append('Authorization', `Bearer ${t.toString()}`);
// new code here
var formData = new FormData();
formData.append('issue',issue); //you need to specify the parameter name here.
this.http.post(`${this.baseUrl}/v1/issues`, formData, {
headers: headers
}).toPromise()
.then(res => {
console.log(res.json());
});
});
}

Hope this helps.



Related Topics



Leave a reply



Submit