Hi rani,
For using WebAPI refer below links.
Check this example. Now please take its reference and correct your code.
Web API Controller
public class CustomerAPIController : ControllerBase
{
[Route("api/CustomerAPI/GetCustomers")]
[HttpPost]
public List<Customer> GetCustomers(Customer customer)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = 1, Name = "John Hammond", Country = "United States" });
customers.Add(new Customer { Id = 2, Name = "Mudassar Khan", Country = "India" });
customers.Add(new Customer { Id = 3, Name = "Suzanne Mathews", Country = "France" });
customers.Add(new Customer { Id = 4, Name = "Robert Schidner", Country = "Russia" });
if (!string.IsNullOrEmpty(customer.Name))
{
customers = customers.Where(x => x.Name.StartsWith(customer.Name)).ToList();
}
return customers;
}
}
Model
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Namespaces
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
List<Customer> customers = SearchCustomers("");
return View(customers);
}
[HttpPost]
public IActionResult Index(string name)
{
List<Customer> customers = SearchCustomers(name);
return View(customers);
}
private static List<Customer> SearchCustomers(string name)
{
string apiUrl = "http://localhost:60557/api/CustomerAPI";
var input = new { Name = name };
string inputJson = JsonConvert.SerializeObject(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/GetCustomers", inputJson);
List<Customer> customers = JsonConvert.DeserializeObject<List<Customer>>(json);
return customers;
}
}
View
@using Consume_API_Core_MVC.Models
@model IEnumerable<Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<span>Name:</span>
<input type="text" name="name" />
<input type="submit" value="Search" />
}
<hr />
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
@foreach (Customer customer in Model)
{
<tr>
<td>@customer.Id</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</tbody>
</table>
</body>
</html>
Screenshot