在ASP.NET MVC中编写API接口,通常可以使用ASP.NET Web API(已整合到ASP.NET Core MVC中)。以下是在ASP.NET MVC中创建API接口的步骤和示例:
1. 创建API控制器
首先,创建一个继承自ApiController(旧版Web API)或ControllerBase(ASP.NET Core)的控制器类。
2. 定义API方法
使用HTTP动词特性(如[HttpGet]、[HttpPost]等)来定义API的访问方式。
3. 配置路由
可以使用特性路由([Route])来定义API的URL路径。
示例代码
下面是一个完整的ASP.NET Core MVC API控制器示例:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespaceMvcApiExample.Controllers
{
    // 定义API路由前缀
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        // 模拟数据库
        private static readonly List<Product> _products = new List<Product>
        {
            new Product { Id = 1, Name = "笔记本电脑", Price = 5999.99m },
            new Product { Id = 2, Name = "智能手机", Price = 3999.99m }
        };
        // GET: api/Products
        [HttpGet]
        public ActionResult<IEnumerable<Product>> GetProducts()
        {
            return _products;
        }
        // GET: api/Products/5
        [HttpGet("{id}")]
        public ActionResult<Product> GetProduct(int id)
        {
            var product = _products.Find(p => p.Id == id);
            if (product == null)
            {
                return NotFound(); // 返回404
            }
            return product;
        }
        // POST: api/Products
        [HttpPost]
        public ActionResult<Product> PostProduct(Product product)
        {
            _products.Add(product);
            // 返回201 Created,并包含新创建资源的URL
            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
        }
        // PUT: api/Products/5
        [HttpPut("{id}")]
        public IActionResult PutProduct(int id, Product product)
        {
            if (id != product.Id)
            {
                return BadRequest(); // 返回400
            }
            var existingProduct = _products.Find(p => p.Id == id);
            if (existingProduct == null)
            {
                return NotFound(); // 返回404
            }
            // 更新产品信息
            existingProduct.Name = product.Name;
            existingProduct.Price = product.Price;
            return NoContent(); // 返回204
        }
        // DELETE: api/Products/5
        [HttpDelete("{id}")]
        public IActionResult DeleteProduct(int id)
        {
            var product = _products.Find(p => p.Id == id);
            if (product == null)
            {
                return NotFound(); // 返回404
            }
            _products.Remove(product);
            return NoContent(); // 返回204
        }
    }
    // 产品模型类
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}
代码说明
- 
控制器配置: - [Route("api/[controller]")]定义了API的基础路径,例如- api/products
- [ApiController]启用了API特定的行为,如自动模型验证和HTTP 400响应
 
- 
HTTP方法: - [HttpGet]:获取资源
- [HttpPost]:创建新资源
- [HttpPut]:更新资源
- [HttpDelete]:删除资源
 
- 
返回类型: - 使用ActionResult<T>可以返回多种结果类型(如数据、错误状态码等)
- 常用状态码:200(Ok)、201(Created)、204(NoContent)、400(BadRequest)、404(NotFound)
 
- 使用
- 
模型绑定: - 输入参数会自动从请求中绑定(URL、表单数据、JSON等)
 
测试API
可以使用工具如Postman、curl或浏览器来测试API:
- GET: https://localhost:5001/api/products获取所有产品
- GET: https://localhost:5001/api/products/1获取ID为1的产品
- POST: 向https://localhost:5001/api/products发送JSON数据创建产品
这种方式创建的API遵循RESTful设计原则,可以很容易地与前端应用程序或其他服务进行集成。










