Skip to main content

How to POST data from Angular in .NET 6 API

 To send data from an Angular application to a .NET 6 API using a POST request, you can follow these steps:

  1. In your Angular application, import the HttpClient module from @angular/common/http.
typescript
import { HttpClient } from '@angular/common/http';
  1. Inject the HttpClient service into your component or service.
typescript
constructor(private http: HttpClient) { }
  1. Define the data you want to send as an object.
typescript
const data = { name: 'John Doe', email: 'johndoe@example.com' };
  1. Send the POST request to the API endpoint using the HttpClient service. The post() method takes two arguments: the API endpoint URL and the data object to be sent.
typescript
this.http.post('/api/endpoint', data).subscribe(response => { console.log(response); });
  1. In your .NET 6 API, define a controller action that accepts the POST request and the data object. You can use the [FromBody] attribute to specify that the data should be deserialized from the request body.
csharp
[HttpPost] public IActionResult Endpoint([FromBody] MyModel model) { // Process the data as needed return Ok(); }
  1. Define a model class that matches the structure of the data being sent from the Angular application.
csharp
public class MyModel { public string Name { get; set; } public string Email { get; set; } }
  1. The data sent from the Angular application will be automatically deserialized into an instance of the MyModel class, which can be used to process the data in the controller action.

That's it! You can now send data from your Angular application to your .NET 6 API using a POST request.

Comments