Hi @Kuldeep Y ,
now i want to call api from my client project to server project where i have made my controller and data access method from database,
Below is a work demo you can refer to it.
- In server project Program.cs add the code:
builder.Services.AddControllers();
builder.Services.AddHttpClient();
...
app.MapControllers();
app.Run();
2.Values api controller (this for test , you can use your controller):
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly BlazorApp8ControllerContext _context;
public ValuesController(BlazorApp8ControllerContext context)
{
_context = context;
}
// GET: api/Values
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUser()
{
return await _context.User.ToListAsync();
}
}
3.In client project add the model(the same model with the server project) to access the data,
User (the model for test, you can use your model):
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
and a GetDataComponent.razor:
@page "/getdata"
@using BlazorApp8Controller.Client.Models
<h3>GetDataComponent</h3>
@inject HttpClient Http
@if (todoItems == null)
{
<p>No Todo Items found.</p>
}
else
{
<ul>
@foreach (var item in todoItems)
{
<li>@item.Name</li>
}
</ul>
}
@code {
private List<User> todoItems;
protected override async Task OnInitializedAsync() =>
todoItems = await Http.GetFromJsonAsync<List<User>>("https://localhost:7281/api/values");//for test, you can use your uri
}
3.result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Qing Guo