Consume API in MVC Application
To map the response from API (
https://localhost:7264/api/Product
) to a .NET MVC Web App, you need to call the API from your controller and deserialize the response into a model, which you can then pass to a view.1: Create the Product Model
2: Call API from MVC Controller
3: Register
HttpClient
in Program.cs
(or Startup.cs
)4: Create the Razor View (
Views/Product/Index.cshtml
)5: Route to Controller
Step 1: Create the Product Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Step 2: Call API from MVC Controller
using Microsoft.AspNetCore.Mvc;
using ProductManagementMVC.Models;
using System.Net.Http.Headers;
using System.Text.Json;
namespace ProductManagementMVC.Controllers
{
public class ProductController : Controller
{
private readonly HttpClient _httpClient;
public ProductController(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient();
}
public async Task<IActionResult> Index()
{
var apiUrl = "https://localhost:7264/api/Product";
var request = new HttpRequestMessage(HttpMethod.Get, apiUrl);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Use JSON for easier deserialization
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseStream = await response.Content.ReadAsStreamAsync();
var products = await JsonSerializer.DeserializeAsync<List<Product>>(responseStream, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return View(products);
}
else
{
// Handle errors
return View(new List<Product>());
}
}
}
}
Step 3: Register
HttpClient
in Program.cs
builder.Services.AddHttpClient();
Step 4: Create the Razor View (
Views/Product/Index.cshtml
)@model List<ProductManagementMVC.Models.Product>
<h2>Product List</h2>
<table class="table">
<thead>
<tr>
<th>ProdId</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.ProdId</td>
<td>@product.ProductName</td>
<td>@product.Price</td>
</tr>
}
</tbody>
</table>
Step 5: Route to Controller
app.MapControllerRoute(
name: "default",
pattern: "{controller=Product}/{action=Index}/{id?}");
Comments
Post a Comment