I have an angular client that has an angular JSON editor. I have to send the JSON data (from the editor) to a .NET Core Web API controller and there I have to perform tasks like writing it into a JSON file. How do I approach this? I need help and more with the controller.
1 Answer
I have to send the JSON data (from the editor) to a .NET Core Web API controller and there I have to perform tasks like writing it into a JSON file. How do I approach this?
To achieve the above requirement, you can refer to following code snippet.
Angular client
@ViewChild(JsonEditorComponent) editor: JsonEditorComponent;
options = new JsonEditorOptions();
data = {
name: "fei",
age: 28
};
constructor(private httpClient: HttpClient) {
this.options.mode = "code";
this.options.modes = ["code", "text", "tree", "view"];
this.options.schema = schema;
this.options.statusBar = false;
this.options.onChange = () => console.log(this.editor.get());
}
InsertUser() {
const updatedJson = this.editor.get();
const headers = new HttpHeaders().set("Content-Type", "application/json");
this.httpClient
.post("https://xxxxx/Insert", JSON.stringify(updatedJson), {
headers: headers,
responseType: "text"
})
.subscribe(data => {
console.log(data);
});
}
Controller and Action
[HttpPost("/Insert")]
public async Task<IActionResult> InsertUser(User User)
{
//...
return Ok("success");
}
Model class User
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
Test Result
1 Comment
Arunudoy Buragohain
Hi Fei Han, thank you so much for your help. Just one follow up question, here we have a model that is already defined. What if we we have to send a random JSON file. In that case, how will the controller action look like. Here you have already defined the User model. That way the controller can accept any JSON data.
