1 restful api http请求约束规范
2 添加内容协商代码,添加xml格式输出数据
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Routine.Api.Data; using Routine.Api.Services; namespace Routine.Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(configure=> { configure.ReturnHttpNotAcceptable = true; //configure.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); //configure.OutputFormatters.Insert(0,new XmlDataContractSerializerOutputFormatter()); }).AddXmlDataContractSerializerFormatters(); services.AddScoped<ICompanyRepository, CompanyRepository>(); services.AddDbContext<RoutineDbContext>(builder=> { builder.UseSqlite("Data Source=routine.db"); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
3 添加automapper和输出模型dto
AutoMapper.Extensions.Microsoft.DependencyInjection
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Routine.Api.Models { public class CompanyDto { public Guid Id { get; set; } public string CompanyName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Routine.Api.Models { public class EmployeeDto { public Guid Id { get; set; } public Guid CompanyId { get; set; } public string EmployeeNo { get; set; } public string Name { get; set; } public string GenderDisplay { get; set; } public int Age { get; set; } } }
using AutoMapper; using Routine.Api.Entities; using Routine.Api.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Routine.Api.Profiles { public class CompanyProfile:Profile { public CompanyProfile() { CreateMap<Company, CompanyDto>() .ForMember(dest => dest.CompanyName, opt => opt.MapFrom(src => src.Name)); } } }
using AutoMapper; using Routine.Api.Entities; using Routine.Api.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Routine.Api.Profiles { public class EmployeeProfile : Profile { public EmployeeProfile() { CreateMap<Employee, EmployeeDto>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}")) .ForMember(dest => dest.GenderDisplay, opt => opt.MapFrom(src => src.Gender.ToString())) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => DateTime.Now.Year-src.DateOfiBirth.Year)) ; } } }
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
4 编写控制器类
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Routine.Api.Models; using Routine.Api.Services; namespace Routine.Api.Controllers { //[Route("api/[controller]")] [Route("api/companies")] [ApiController] public class CompaniesController : ControllerBase { private readonly ICompanyRepository _companyRepository; private readonly IMapper _mapper; public CompaniesController(ICompanyRepository companyRepository,IMapper mapper) { _companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository)); this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); } [HttpGet] public async Task<ActionResult<IEnumerable<CompanyDto>>> GetCompaniesAsync() { var companies = await _companyRepository.GetCompaniesAsync(); //var companyDtos = new List<CompanyDto>(); //foreach(var company in companies) //{ // companyDtos.Add(new CompanyDto { // Id=company.Id, // Name=company.Name // }); //} var companyDtos = _mapper.Map<IEnumerable<CompanyDto>>(companies); return Ok(companyDtos); } [HttpGet("{companyId}")] public async Task<ActionResult<CompanyDto>> GetCompaniesAsync(Guid companyId) { var company = await _companyRepository.GetCompanyAsync(companyId); if (company == null) { return NotFound(); } var companyDto = _mapper.Map<CompanyDto>(company); return Ok(companyDto); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Routine.Api.Models; using Routine.Api.Services; namespace Routine.Api.Controllers { //[Route("api/[controller]")] [Route("api/companies/{companyId}/employees")] [ApiController] public class EmployeesController : ControllerBase { private readonly ICompanyRepository _companyRepository; private readonly IMapper _mapper; public EmployeesController(ICompanyRepository companyRepository,IMapper mapper) { _companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository)); this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); } [HttpGet] public async Task<ActionResult<IEnumerable<EmployeeDto>>> GetEmployeesByCompanyIdAsync(Guid companyId) { if (!await _companyRepository.CompanyExistsAsync(companyId)) { return NotFound(); } var employees = await _companyRepository.GetEmployeesAsync(companyId); var employeeDtos = _mapper.Map<IEnumerable<EmployeeDto>>(employees); return Ok(employeeDtos); } [HttpGet("{employeeId}")] public async Task<ActionResult<EmployeeDto>> GetEmployeeByCompanyIdAsync(Guid companyId,Guid employeeId) { if (!await _companyRepository.CompanyExistsAsync(companyId)) { return NotFound(); } var employee = await _companyRepository.GetEmployeesAsync(companyId, employeeId); if (employee==null) { return NotFound(); } EmployeeDto employeeDto = _mapper.Map<EmployeeDto>(employee); return Ok(employeeDto); } } }