| using Microsoft.AspNetCore.Mvc;
|
| using System;
|
| using System.Collections.Generic;
|
| using System.Linq;
|
| using System.Threading.Tasks;
|
| |
| namespace MyWebApi.Controllers
|
| {
|
| [ApiController]
|
| [Route("[controller]")]
|
| public class WeatherForecastController : ControllerBase
|
| {
|
| private static readonly Random _random = new Random();
|
| |
| [HttpGet(Name = "GetWeatherForecast")]
|
| public IEnumerable<WeatherForecast> Get()
|
| {
|
| var rng = new Random();
|
| return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
| {
|
| Date = DateTime.Now.AddDays(index),
|
| TemperatureC = rng.Next(-20, 55),
|
| Summary = Summaries[rng.Next(Summaries.Length)]
|
| })
|
| .ToArray();
|
| }
|
| |
| private static readonly string[] Summaries = new[]
|
| {
|
| "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
| };
|
| |
| public class WeatherForecast
|
| {
|
| public DateTime Date { get; set; }
|
| |
| public int TemperatureC { get; set; }
|
| |
| public string Summary { get; set; }
|
| }
|
| }
|
| }
|
在上面的代码中,我们界说了一个WeatherForecastController类,而且使用了[ApiController]和[Route("[controller]")]属性来指定这是一个API控制器,而且其路由将基于控制器名称。 | using Microsoft.AspNetCore.Mvc;
|
| using Microsoft.EntityFrameworkCore;
|
| using MyWebApiWithEF.Data;
|
| using MyWebApiWithEF.Models;
|
| using System.Collections.Generic;
|
| using System.Linq;
|
| using System.Threading.Tasks;
|
| |
| namespace MyWebApiWithEF.Controllers
|
| {
|
| [ApiController]
|
| [Route("[controller]")]
|
| public class ProductsController : ControllerBase
|
| {
|
| private readonly ApplicationDbContext _context;
|
| |
| public ProductsController(ApplicationDbContext context)
|
| {
|
| _context = context;
|
| }
|
| |
| // GET: api/products
|
| [HttpGet]
|
| public async Task<ActionResult<IEnumerable< roduct>>> GetProducts()
|
| {
|
| return await _context.Products.ToListAsync();
|
| }
|
| |
| // 其他CRUD操作...
|
| }
|
| }
|
现在,你可以运行你的Web API项目,并使用HTTP GET请求来访问http://localhost:5000/products,以获取所有的Product数据。