基於asp.net core webapi的商品管理系統Api開發 必備基礎知識
阿新 • • 發佈:2020-06-14
1automapper
.NET CORE 中使用AutoMapper進行物件對映
參考文件:
https://blog.csdn.net/weixin_37207795/article/details/81009878
配置程式碼
using AutoMapper; using System; using System.Collections.Generic; using System.Text; using Xwy.Domain.Dtos.Product; using Xwy.Domain.Dtos.UserInfo; using Xwy.Domain.Entities; namespace Xwy.Domain {public class AutoMapperConfigs : Profile { //新增你的實體對映關係. public AutoMapperConfigs() { //Product轉ProductDto. CreateMap<Product,ProductDto>() //對映發生之前 .BeforeMap((source,dto) => { //可以較為精確的控制輸出資料格式//dto.CreateTime = Convert.ToDateTime(source.CreateTime).ToString("yyyy-MM-dd"); }) //對映發生之後 .AfterMap((source,dto) => { //code ... }); //UserInfoDto轉UserInfo. CreateMap<UserInfoDto,UserInfo>(); CreateMap<UserInfo,UserInfoDto>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Xwy.Domain; using Xwy.Domain.DbContexts; using Xwy.Domain.Dtos.UserInfo; using Xwy.Domain.Entities; namespace Xwy.WebApiDemo.Controllers { [Route("api/[controller]")] [ApiController] public class UserInfoesController : ControllerBase { private readonly VueShopDbContext _context; private readonly IMapper _mapper; public UserInfoesController(VueShopDbContext context,IMapper mapper) { _context = context; _mapper = mapper; } // GET: api/UserInfoes [HttpGet] public async Task<ActionResult<IEnumerable<UserInfo>>> GetUserInfos() { return await _context.UserInfos.ToListAsync(); } // GET: api/UserInfoes/5 [HttpGet("{id}")] public async Task<ActionResult<UserInfo>> GetUserInfo(int id) { var userInfo = await _context.UserInfos.FindAsync(id); if (userInfo == null) { return NotFound(); } return userInfo; } // PUT: api/UserInfoes/5 // To protect from overposting attacks,enable the specific properties you want to bind to,for // more details,see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutUserInfo(int id,UserInfo userInfo) { if (id != userInfo.Id) { return BadRequest(); } _context.Entry(userInfo).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserInfoExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/UserInfoes // To protect from overposting attacks,see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task<ActionResult<UserInfo>> PostUserInfo(UserInfoDto userInfoDto) { if (UserInfoExists(userInfoDto.UserName)) return BadRequest("使用者名稱已存在!"); UserInfo userInfo = _mapper.Map<UserInfo>(userInfoDto); _context.UserInfos.Add(userInfo); await _context.SaveChangesAsync(); return CreatedAtAction("GetUserInfo",new { id = userInfo.Id },userInfo); } // DELETE: api/UserInfoes/5 [HttpDelete("{id}")] public async Task<ActionResult<UserInfo>> DeleteUserInfo(int id) { var userInfo = await _context.UserInfos.FindAsync(id); if (userInfo == null) { return NotFound(); } _context.UserInfos.Remove(userInfo); await _context.SaveChangesAsync(); return userInfo; } private bool UserInfoExists(int id) { return _context.UserInfos.Any(e => e.Id == id); } private bool UserInfoExists(string userName) { return _context.UserInfos.Any(e => e.UserName == userName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using Xwy.Domain; using Xwy.Domain.DbContexts; namespace Xwy.WebApiDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ClothersMallDbContext>(m=> { }); services.AddDbContext<VueShopDbContext>(m => { }); services.AddAutoMapper(typeof(AutoMapperConfigs));//註冊automapper服務 services.AddSwaggerGen(m => { m.SwaggerDoc("v1",new OpenApiInfo() { Title="swaggertest",Version="v1"}); }); services.AddCors(m => m.AddPolicy("any",a => a.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app,IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseSwagger(); app.UseCors(); app.UseSwaggerUI(m=> { m.SwaggerEndpoint("/swagger/v1/swagger.json","swaggertest"); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }