VS创建WebApi项目过程:
- The client can decide json or xml format it wants by setting the "Accept" header in the HTTP request message.
添加Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApiTest.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
添加控制器
- In Web API, a controller is an object that handles HTTP requests.
- You don't need to put your controllers into a folder named Controllers. The folder name is just a convenient way to organize your source files.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiTest.Models;
namespace WebApiTest.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
- GetAllProducts 请求路径为: /api/products
- GetProduct 请求路径为:/api/products/id
运行
网页
PostMan