码迷,mamicode.com
首页 > Windows程序 > 详细

基于asp.net core webapi的商品管理系统Api开发 必备基础知识

时间:2020-06-14 16:50:07      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:file   ica   runtime   origin   enum   tps   配置   depend   iap   

1 automapper

.NET CORE 中使用AutoMapper进行对象映射

参考文档:

https://blog.csdn.net/weixin_37207795/article/details/81009878

2 路由基础

参考文档:

https://www.cnblogs.com/aehyok/p/3449851.html

配置代码

 

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, enable the specific properties you want to bind to, for
        // more details, 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();
            });
        }
    }
}

 

基于asp.net core webapi的商品管理系统Api开发 必备基础知识

标签:file   ica   runtime   origin   enum   tps   配置   depend   iap   

原文地址:https://www.cnblogs.com/xiewenyu/p/13125117.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!