基于.NET6平台开发WebApi(九)—— 添加Autofac支持

基于NET6平台WebApi尝鲜项目: 基于最新的.NET6平台,完全抛弃繁杂的接口,采用.NET最经典的三层架构,结合简化的DDD设计模式... (gitee.com)

仓储已经成功注入到项目中,接下来我们基于Address来实现简单的CRUD操作

1、为了更好的开发,我们先定义一个通用的返回结构,并在BaseController中实现几个实例化方法和一些通用方法,代码如下

using Microsoft.AspNetCore.Mvc;
using NET6.Domain.ViewModels;
using Serilog;
using System.Security.Claims;

namespace NET6.Api.Controllers
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    //[Authorize]
    [ApiController]
    public class BaseController : ControllerBase
    {
        protected virtual string? CurrentUserId => HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        protected virtual void Logs(string str)
        {
            Log.Error(str);
        }
        protected virtual JsonView JsonView(object obj)
        {
            return new JsonView { Code = StatusCodes.Status200OK, Msg = "操作成功", Data = obj };
        }
        protected virtual JsonView JsonView(object obj, int count)
        {
            return new JsonView { Code = StatusCodes.Status200OK, Msg = "操作成功", Data = obj, Count = count };
        }
        protected virtual JsonView JsonView(string msg)
        {
            return new JsonView { Code = StatusCodes.Status400BadRequest, Msg = msg };
        }
        protected virtual JsonView JsonView(bool s)
        {
            if (s)
            {
                return new JsonView { Code = StatusCodes.Status200OK, Msg = "操作成功" };
            }
            else
            {
                return new JsonView { Code = StatusCodes.Status400BadRequest, Msg = "操作失败" };
            }
        }
        protected virtual JsonView JsonView(bool s, string msg)
        {
            if (s)
            {
                return new JsonView { Code = StatusCodes.Status200OK, Msg = msg };
            }
            else
            {
                return new JsonView { Code = StatusCodes.Status400BadRequest, Msg = msg };
            }
        }
    }
}

2、我们基于Restful方式为Address创建CRUD方法,代码如下

using Microsoft.AspNetCore.Mvc;
using NET6.Domain.Dtos;
using NET6.Domain.Entities;
using NET6.Domain.ViewModels;
using NET6.Infrastructure.Repositories;
using SqlSugar;

namespace NET6.Api.Controllers
{
    /// <summary>
    /// 地址相关接口
    /// </summary>
    [Route("address")]
    public class AddressController : BaseController
    {
        readonly AddressRepository _addressRep;
        public AddressController(AddressRepository addressRep)
        {
            _addressRep = addressRep;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="size">每页条数</param>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(List<AddressView>), StatusCodes.Status200OK)]
        public async Task<IActionResult> ListAsync(int page = 1, int size = 15)
        {
            var query = _addressRep.QueryDto(a => !a.IsDeleted);
            RefAsync<int> count = 0;
            var list = await query.OrderBy(a => a.IsDefault).ToPageListAsync(page, size, count);
            return Ok(JsonView(list, count));
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<IActionResult> AddAsync(AddressDto dto)
        {
            try
            {
                //开启事务
                _addressRep.BeginTran();
                var result = await _addressRep.AddAsync(new Address
                {
                    UserId = CurrentUserId,
                    Name = dto.Name,
                    Phone = dto.Phone,
                    Province = dto.Province,
                    City = dto.City,
                    Area = dto.Area,
                    Detail = dto.Detail,
                    IsDefault = dto.IsDefault
                });
                _addressRep.CommitTran();
                if (result > 0) return Ok(JsonView(true));
                return Ok(JsonView(false));
            }
            catch (Exception e)
            {
                _addressRep.RollbackTran();
                Logs("添加异常:" + e.Message);
                return Ok(JsonView("添加异常"));
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="Id">编号</param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("{Id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<IActionResult> EditAsync(string Id, AddressDto dto)
        {
            try
            {
                //开启事务
                _addressRep.BeginTran();
                var result = await _addressRep.UpdateAsync(a => a.Id == Id, a => new Address
                {
                    Name = dto.Name,
                    Phone = dto.Phone,
                    Province = dto.Province,
                    City = dto.City,
                    Area = dto.Area,
                    Detail = dto.Detail,
                    IsDefault = dto.IsDefault
                });
                _addressRep.CommitTran();
                if (result) return Ok(JsonView(true));
                return Ok(JsonView(false));
            }
            catch (Exception e)
            {
                _addressRep.RollbackTran();
                Logs("修改异常:" + e.Message);
                return Ok(JsonView("修改异常"));
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id">编号</param>
        /// <returns></returns>
        [HttpDelete("{Id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<IActionResult> DeleteAsync(string Id)
        {
            try
            {
                //开启事务
                _addressRep.BeginTran();
                var result = await _addressRep.DeleteAsync(a => a.Id == Id);
                _addressRep.CommitTran();
                if (result) return Ok(JsonView(true));
                return Ok(JsonView(false));
            }
            catch (Exception e)
            {
                _addressRep.RollbackTran();
                Logs("删除异常:" + e.Message);
                return Ok(JsonView("删除异常"));
            }
        }

    }
}

3、至此,一个基于Address的Restful风格简单的CRUD接口便开发完成。

 

posted @ 2022-01-05 11:06  昨夜丶雨疏风骤  阅读(1918)  评论(0编辑  收藏  举报