netCore WebAPI基础1

netCore WebAPI基础1

Restfule

特点

  • 无状态
  • 面向资源,即访问地址时使用的是名词形式
  • 使用HTTP动词

使用情况

  • 适用:面向资源,如增删改查
  • 不适用:面向过程,如登陆

Restfule成熟度

  1. L0:只需要api访问即可
  2. L1:面向资源
    写成api/touristRoutes而不是api/getTouristRoutes
  3. L2:使用HTTP动词
    利用GET\POST\PUT\PATCH\DELETE来区分操作
  4. L3:超媒体控制
    api的自我发现,即返回一个资源时,附带着返回对这条资源操作的相关链接

状态码

级别常见状态码
1xx不常用
2xx200:ok,201:created,201:No Content
3xx301/302:Moved Permanently,304:Not Modified
4xx400:Bad Request,401:Unauthorized,403:Forbidden,404:Not Found
5xx500:Internal Servel Error,502:Gateway

内容协商

浏览器会在头文件中的Accept下协商内容的格式,如application/json。
.netCore默认是返回Json格式可以在program中修改:

1
2
3
4
builder.Services.AddControllers(opt => {
opt.ReturnHttpNotAcceptable = true;//默认是false,即只识别和返回json类型
opt.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());//可以返回xml类型,老方法,已经弃用
}).AddXmlDataContractSerializerFormatters();//新方法,可以输入和输入xml格式的内容

DTO

数据模型(Model)包含了很多不需要展示的信息。将需要展示的信息提取形成DTO模型对象

  1. Nuget安装AutoMapper.Extensions.Microsoft.DependencyInjection
  2. 创建Dto对象
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    //模型对象
    public class TouristRoute
    {
    [Key]
    public Guid Id { get; set; }
    [Required]
    [MaxLength(100)]
    public string Title { get; set; }
    [Required]
    [MaxLength(1500)]
    public string Description { get; set; }
    [Column(TypeName = "decimal(18, 2)")]
    public decimal OriginalPrice { get; set; }
    [Range(0.0, 1.0)]
    public double? DiscountPresent { get; set; }
    public DateTime CreateTime { get; set; }
    public DateTime? UpdateTime { get; set; }
    public DateTime? DepartureTime { get; set; }
    [MaxLength]
    public string Features { get; set; }
    [MaxLength]
    public string Fees { get; set; }
    [MaxLength]
    public string Notes { get; set; }
    public double? Rating { get; set; }
    public TravelDays? TravelDays { get; set; }
    public TripType? TripType { get; set; }
    public DepartureCity? DepartureCity { get; set; }
    }
    //DTO对象
    public class TouristRouteDto
    {
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }// 计算方式:原价 * 折扣
    public DateTime CreateTime { get; set; }
    public DateTime? UpdateTime { get; set; }
    public DateTime? DepartureTime { get; set; }
    public string Features { get; set; }
    public string Fees { get; set; }
    public string Notes { get; set; }
    public double? Rating { get; set; }
    public string TravelDays { get; set; }// 枚举变成了string
    public string TripType { get; set; }// 枚举变成了string
    public string DepartureCity { get; set; }// 枚举变成了string
    }
  3. 注册AutoMapper
    1
    2
    3
    //会自动扫描Profiles文件夹,对里面的映射设置进行处理
    //扫描程序集中所有包含映射关系的profile文件并加载
    builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
  4. 创建Profiles文件夹,并在里面增加映射文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class TouristRouteProfile:Profile
    {
    public TouristRouteProfile()
    {
    //默认自动匹配名称相同的字段
    CreateMap<TouristRoute, TouristRouteDto>()
    //其他需要的映射
    .ForMember(dest => dest.Price,
    opt => opt.MapFrom(src => src.OriginalPrice * (decimal)(src.DiscountPresent ?? 1)))
    .ForMember(dest => dest.TravelDays,
    opt => opt.MapFrom(src => src.TravelDays.ToString()))
    .ForMember(dest => dest.TripType,
    opt => opt.MapFrom(src => src.TripType.ToString()))
    .ForMember(dest => dest.DepartureCity,
    opt => opt.MapFrom(src => src.DepartureCity.ToString())
    );
    }
    }
  5. 在控制器中使用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    [Route("api/[controller]")]
    [ApiController]
    public class TouristRoutesController : ControllerBase
    {
    private ITourisTouteRepository _tourisTouteRepository;
    private readonly IMapper _mapper;//增加注入
    public TouristRoutesController(ITourisTouteRepository tourisTouteRepository, IMapper mapper)
    {
    _tourisTouteRepository = tourisTouteRepository;
    _mapper = mapper;
    }
    [HttpGet]
    public IActionResult GetTouristRoutes()
    {
    var routes = _tourisTouteRepository.GetTourisRoutes();
    if (routes == null || routes.Count()<=0)
    {
    return NotFound("没有旅游路线");
    }
    //使用映射
    var touristRouteDto = _mapper.Map<IEnumerable<TouristRouteDto>>(routes);
    return Ok(touristRouteDto);
    }
    }
作者

步步为营

发布于

2024-06-04

更新于

2025-03-15

许可协议