ASP.NET Core Web API 可以很容易地与前端(如 JavaScript、HTML、CSS 等)进行交互。这里是一个简单的示例,展示了如何使用 ASP.NET Core Web API 与前端进行交互。
首先,创建一个简单的 ASP.NET Core Web API。在 Visual Studio 中,创建一个新的 ASP.NET Core Web 应用,然后选择 “API” 作为项目模板。
在项目中添加一个模型类。例如,创建一个名为 Employee
的类:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
}
Startup.cs
文件中,配置 Web API 路由:public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
EmployeesController
的控制器:using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
private static List<Employee> employees = new List<Employee>
{
new Employee { Id = 1, Name = "John Doe", Position = "Software Engineer" },
new Employee { Id = 2, Name = "Jane Smith", Position = "Project Manager" }
};
[HttpGet]
public ActionResult<IEnumerable<Employee>> GetEmployees()
{
return Ok(employees);
}
[HttpGet("{id}")]
public ActionResult<Employee> GetEmployee(int id)
{
var employee = employees.Find(e => e.Id == id);
if (employee == null)
{
return NotFound();
}
return Ok(employee);
}
[HttpPost]
public ActionResult<Employee> PostEmployee(Employee employee)
{
employees.Add(employee);
return CreatedAtAction(nameof(GetEmployee), new { id = employee.Id }, employee);
}
[HttpPut("{id}")]
public IActionResult PutEmployee(int id, Employee employee)
{
if (id != employee.Id)
{
return BadRequest();
}
employees[employees.IndexOf(employee)] = employee;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteEmployee(int id)
{
var employee = employees.Find(e => e.Id == id);
if (employee == null)
{
return NotFound();
}
employees.Remove(employee);
return NoContent();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASP.NET Core Web API Example</title>
</head>
<body>
<h1>Employees</h1>
<button id="getEmployeesBtn">Get Employees</button>
<ul id="employeesList"></ul>
<script>
document.getElementById('getEmployeesBtn').addEventListener('click', async () => {
const response = await fetch('/api/employees');
const employees = await response.json();
const employeesList = document.getElementById('employeesList');
employeesList.innerHTML = '';
employees.forEach(employee => {
const listItem = document.createElement('li');
listItem.textContent = `${employee.Name} - ${employee.Position}`;
employeesList.appendChild(listItem);
});
});
</script>
</body>
</html>
在这个示例中,当用户点击 “Get Employees” 按钮时,JavaScript 代码会向 Web API 发送请求以获取员工列表,并将其显示在页面上。你可以根据需要扩展此示例以支持其他操作(如创建、更新和删除员工)。