.net core api开发入门

.net core是微软新一代跨平台软件开发框架,其中Web Blazor服务端渲染,Web API开发及EntityFrameworkCore等都是现在Web开发中必须的,而且开发效率开发体验都很好。今天给大家演示一下如何开发asp.net core web api开发。

1. 新建Web API 项目

2.开发一个基于EntityFrameworkCore.SqlServer的Web API服务

   系统反馈表

#### 系统反馈表
create table Basis_Feedback
(
	FeedbackId int identity
		constraint PK_Basis_Feedback
			primary key,
	Title nvarchar(100) not null,
	Content nvarchar(500) not null,
	InUserId nvarchar(40) not null,
	InUserName nvarchar(40) not null,
	InDate datetime not null,
	CommonStatus int not null
)
go

exec sp_addextendedproperty 'MS_Description', '系统反馈表', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Feedback'
go

exec sp_addextendedproperty 'MS_Description', '系统主键', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Feedback', 'COLUMN', 'Id'
go

exec sp_addextendedproperty 'MS_Description', '反馈主题', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Feedback', 'COLUMN', 'Title'
go

exec sp_addextendedproperty 'MS_Description', '反馈内容', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Feedback', 'COLUMN', 'Content'
go

exec sp_addextendedproperty 'MS_Description', '数据状态', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Feedback', 'COLUMN', 'CommonStatus'
go

create index IX_Basis_Feedback_InDate
	on Basis_Feedback (InDate)
go

    通用附件表

create table dbo.Basis_Attachment
(
	AttachmentId int identity,
	BusinessType int not null,
	BusinessId int not null,
	AttachmentName nvarchar(100) not null,
	AttachmentUrl nvarchar(500) not null,
	AttachmentDescription nvarchar(500) not null,
	InUserId nvarchar(40) not null,
	InUserName nvarchar(40) not null,
	InDate datetime not null,
	CommonStatus int not null,
	constraint PK_Basis_Attachment PRIMARY key(AttachmentId)
)
go

create index IX_Basis_Attachment_BusinessType_BusinessId ON dbo.Basis_Attachment(BusinessType,BusinessId)
go

exec sp_addextendedproperty 'MS_Description', '系统反馈表', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Attachment'
go

exec sp_addextendedproperty 'MS_Description', '系统主键', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Attachment', 'COLUMN', 'Id'
go

exec sp_addextendedproperty 'MS_Description', '业务类型,参建代码中的枚举定义', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Attachment', 'COLUMN', 'BusinessType'
go

exec sp_addextendedproperty 'MS_Description', '业务主键编号', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Attachment', 'COLUMN', 'BusinessId'
go

exec sp_addextendedproperty 'MS_Description', '数据状态', 'SCHEMA', 'dbo', 'TABLE', 'Basis_Attachment', 'COLUMN', 'CommonStatus'
go

 

    配置DbContext

public class BasisDataContext : DbContext
    {
        public DbSet Feedback { get; set; }

        public BasisDataContext(DbContextOptions options) : base(options)
        {
        }
    }

在appsettings.Development.json中增加链接字符串

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ConnectionStrings": {
    "OADB": "Data Source=,;Initial Catalog=oa;Uid=sa;Pwd=;Integrated Security=false;timeout=900"
  }
}

在Startup.cs中配置使用中间件Microsoft.EntityFrameworkCore.SqlServer

services.AddDbContext(options=>
            {
                options.UseSqlServer(Configuration.GetConnectionString("OADB"));
            });

            services.AddScoped();

其中的BsisDataContext会被DependencyInjection自动注册为Scoped组件,在服务实现中可以在构造函数中注入:

public class FeedbackServiceImpl : FeedbackService
    {
        private BasisDataContext _basisDataContext;
        public FeedbackServiceImpl(BasisDataContext basisDataContext)
        {
            _basisDataContext = basisDataContext;
        }

        public int Insert(Feedback feedback)
        {
            _basisDataContext.Feedback.Add(feedback);
            _basisDataContext.SaveChanges();

            return feedback.FeedbackId;
        }
    }

接下来就是定义ApiController了

[Route("api/[controller]")]
    [ApiController]
    public class FeedbackController : ControllerBase
    {
        private FeedbackService _feedbackService;
        
        public FeedbackController(FeedbackService feedbackService)
        {
            _feedbackService = feedbackService;
        }
        
        [HttpGet]
        public IEnumerable Get()
        {
            var loginUser = new LoginUser
            {
                UserID = "1162V5100000000000UX",
                LoginName = "james.h.fu",
                DisplayName = "fuhongwei",
                CompanyID = "88888"
            };
            
            var feedback = new Feedback
            {
                Title = "test",
                Content = "截图总是不成功",
                InUserId = loginUser.UserID,
                InUserName = loginUser.DisplayName,
                InDate = DateTime.Now,
                CommonStatus =  CommonStatusEnum.Valid
            };

            feedback.Attachments.Add(new Attachment
            {
                BusinessType = AttachmentBusinessTypeEnum.Basis_Feedback,
                AttachmentName = "截图报错",
                AttachmentUrl = "oa/feedback/1162V5100000000000UX.jpg",
                AttachmentDescription="",
                InUserId = loginUser.UserID,
                InUserName = loginUser.DisplayName,
                InDate = DateTime.Now,
                CommonStatus =  CommonStatusEnum.Valid
            });

            _feedbackService.Insert(feedback);
            return new string[] { "value1", "value2" };
        }
    }

使用curl测试

curl https://localhost:8000/api/feedback

["value1","value2"]

 

开发过程中遇到的问题:

业务模型中Feedback可以有多个Attachment, 因此会默认Attachment中有一个外键FeedbackId, 但是我设计的这个领域模型是通用的,希望是BusinessId, 因此需要特别声明出来。

[Table("Basis_Feedback")]
    public class Feedback : InsertBaseModel
    {
        public Feedback()
        {
            Attachments = new List();
        }

        /// 
        /// 主键
        /// 
        [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int FeedbackId { get; set; }

        public string Title { get; set; }

        public string Content { get; set; }

        [ForeignKey("BusinessId")]
        public List Attachments { get; set; }
    }

最后将.csproj文件贡献出来给大家参考, 建议大家一定要自己动手实践一下,真的很有意思,很值得学习。



  
    netcoreapp3.0
    ylkj_oa_api
    ylkj_oa_api.Program
  

  
    
    
    
    
      all
      runtime; build; native; contentfiles; analyzers; buildtransitive
    
    
    
    

    
  

  
    
  

参考资料

ASP.NET Core 基础知识

 

#### 关注公众号交流学习
在这里分享一些项目实战过程中遇到过的问题及解决方案。分享学习到的分布式架构及核心技术细节。

 

.net core api开发入门_第1张图片

加我微信,聊一聊

.net core api开发入门_第2张图片

你可能感兴趣的:(.net,core,架构)