netCore WebAPI基础1
原创
©著作权归作者所有:来自51CTO博客作者步_步_为营的原创作品,请联系作者获取转载授权,否则将追究法律责任
Restfule
特点
- 无状态
- 面向资源,即访问地址时使用的是名词形式
- 使用HTTP动词
使用情况
- 适用:面向资源,如增删改查
- 不适用:面向过程,如登陆
Restfule成熟度
- L0:只需要api访问即可
- L1:面向资源
写成api/touristRoutes
而不是api/getTouristRoutes
- L2:使用HTTP动词
利用GET\POST\PUT\PATCH\DELETE
来区分操作 - L3:超媒体控制
api的自我发现,即返回一个资源时,附带着返回对这条资源操作的相关链接
状态码
级别
| 常见状态码
|
1xx
| 不常用
|
2xx
| 200:ok,201:created,201:No Content
|
3xx
| 301/302:Moved Permanently,304:Not Modified
|
4xx
| 400:Bad Request,401:Unauthorized,403:Forbidden,404:Not Found
|
5xx
| 500:Internal Servel Error,502:Gateway
|
内容协商
浏览器会在头文件中的Accept下协商内容的格式,如application/json。
.netCore默认是返回Json格式可以在program中修改:
builder.Services.AddControllers(opt => {
opt.ReturnHttpNotAcceptable = true;//默认是false,即只识别和返回json类型
opt.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());//可以返回xml类型,老方法,已经弃用
}).AddXmlDataContractSerializerFormatters();//新方法,可以输入和输入xml格式的内容
DTO
数据模型(Model)包含了很多不需要展示的信息。将需要展示的信息提取形成DTO模型对象
- Nuget安装
AutoMapper.Extensions.Microsoft.DependencyInjection
- 创建Dto对象
//模型对象
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
}
- 注册AutoMapper
//会自动扫描Profiles文件夹,对里面的映射设置进行处理
//扫描程序集中所有包含映射关系的profile文件并加载
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
- 创建Profiles文件夹,并在里面增加映射文件
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())
);
}
}
- 在控制器中使用
[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);
}
}