How to call post in ASP Core ReactJS app?
P粉733166744
2023-08-17 17:23:05
<p>I currently have the following in my reactjs javascript file</p>
<pre class="brush:php;toolbar:false;">details.js
const response = await fetch('users');</pre>
<p>This will call the mvc controller below</p>
<p>UsersController.cs</p>
<pre class="brush:php;toolbar:false;">private readonly ILogger<userController> _logger;
public userController(ILogger<userController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<user> Get()
{
<code goes here>
}</pre>
<p>The problem is that fetch calls the Get method. How do I call other methods in the controller?
So if I also have some method like this: </p>
<pre class="brush:php;toolbar:false;">[HttpPost]
public IEnumerable<user> UserDetails(string Id)
{
<code goes here>
}
[HttpPost]
public IEnumerable<user> UserInfo(string name, string Id)
{
<code goes here>
}
[HttpId]
public IEnumerable<user> UserId(string firstname, string lastname, string companyId)
{
<code goes here>
}</pre>
<p>How do I call these methods from the details.js file? </p>
<p>Like the following? </p>
<pre class="brush:php;toolbar:false;">const response = await fetch('users/UserInfo'); ?</pre>
You need to tell the .NET framework about the endpoint parameters and use the correct HTTP method to make the call. For example, changing the code slightly, you can use the Id parameter of the UserDetails method as a URL segment:
TheHttpPost attribute tells the .NET Framework that this is a POST endpoint. Note the {Id} part in the HttpPost attribute. It's a placeholder and you should replace it with the actual ID when calling the endpoint. To call this endpoint, you need to send an HTTP POST request to the "users/123" endpoint, where the "123" part is a replacement for the {Id} placeholder. Here is an example:
Endpoint URLs can also contain query string parameters. For example, here's how to call the UserInfo endpoint using query string parameters:
Note that we added the FromQuery attribute to the "name" parameter of the UserInfo method. The FromQuery attribute tells the .NET Framework that the URL should contain a query string parameter named name. Your endpoint URL will become "users/123?name=john", where "123" is the replacement of the {Id} placeholder and name=john is the assignment of the "name" query string parameter for "john".