.Net core WebApi dapper Autofac依赖注入 前端Vue
本项目采用 .Net core WebApi dapper Autofac依赖注入 前端Vue
前后端分离是主流,AutoFac的依赖注入简单方便,Vue实现前端分离,dappper轻便快捷的数据库框架
1. 文件=》新建项目 选中asp.net core
2.下载Nuget包
Autofac Autofac.Extensions.DependencyInjection (Autofac依赖包)
Dapper (dapper数据库框架)
Swashbuckle.AspNetCore (Swagger 强大的API管理)
System.Configuration.ConfigurationManager (ConfigurationManager 连接数据库要用的,查找配置文件)
3.新建Controllers文件夹 ,在这新建ProductController
using CoreBackend.Api.Dtos;
using CoreBackend.Api.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace CoreBackend.Api.Controllers
{
[Route("api/[controller]")]
public class ProductController : Controller
{
// private IProductService productService;
// private IRankService rankService;//属性注入
public IProductService productService { get; set; }
public IRankService rankService { get; set; }
[HttpGet]
public JsonResult GetProducts()
{
return new JsonResult(productService.GetUsers());
}[HttpGet("getrank")]
public JsonResult GetRank()
{
return new JsonResult(rankService.GetRanks());
}
}
}
[Route("api/[controller]")] [controller] 就是 product ,我们会在startup那里配置controller 自动注入
4. 新建Dtos文件夹,新建Users类,Ranks类(作为实体类),自己在你的数据库里建Users和Ranks表作为测试数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace CoreBackend.Api.Dtos
{
/*
* Mors
* 用户类
* */
//用户信息
public class Users
{
//用户adid
public string adid
{
get; set;
}
//用户编号
public string usercode
{
get; set;
}
//用户中文名
public string usernamecn
{
get; set;
}
//用户英文名
public string usernameen
{
get; set;
}
//用户等级 1:初级 2:中级 3:高级 4:经理
public string rank
{
get; set;
}
//删除标识 0为正常 1为删除
public int delflag
{
get; set;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace CoreBackend.Api.Dtos
{
public class Ranks
{
public string rankname
{
get;set;
}
public string rankcode
{
get;set;
}
}
}
5.新建Services文件夹 RankService ProductService 类 IRankService IProductService 接口
IProductService
using CoreBackend.Api.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace CoreBackend.Api.Services
{
public interface IProductService
{
ListGetUsers();
}
}
IRankService
using CoreBackend.Api.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace CoreBackend.Api.Services
{
public interface IRankService
{
ListGetRanks();
}
}
ProductService
using CoreBackend.Api.Dtos;
using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;namespace CoreBackend.Api.Services
{
public class ProductService: IProductService
{
public List
GetUsers()
{
using (IDbConnection connection = new SqlConnection(ConfigurationManager.AppSettings["SqlserverConnString"]))//连接数据库查询Users表
{string sqlText = "select * from Users";
Listlist = connection.Query (sqlText).ToList();
return list;
}
}
}
}
RankService
using CoreBackend.Api.Dtos;
using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;namespace CoreBackend.Api.Services
{
public class RankService:IRankService
{
public ListGetRanks()
{
using (IDbConnection connection = new SqlConnection(ConfigurationManager.AppSettings["SqlserverConnString"]))
{string sqlText = "select * from Ranks";
Listlist = connection.Query (sqlText).ToList();
return list;
}
}
}
}
6.修改startup代码(swagger配置和autofac配置都在这配置)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using CoreBackend.Api.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
namespace CoreBackend.Api
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public IServiceProvider ConfigureServices(IServiceCollection services)
{/*
*因为asp.net core 使用了一个大而全的metapackage,
* 所以这些基本的services和middleware是不需要另外安装的.
首先, 在ConfigureServices里面向Container注册MVC: services.AddMvc();
*/services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddControllersAsServices();
services.AddCors(_option => _option.AddPolicy("AllowCors", _builder => _builder.AllowAnyOrigin().AllowAnyMethod()));services.AddSwaggerGen(c =>
{//swagger配置https://www.cnblogs.com/yilezhu/p/9241261.html 一定要看,详细解释如何配置swagger 很快速
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "CoreBackend.Api.xml");
c.IncludeXmlComments(xmlPath);
});
//依赖注入Service ,麻烦没新建一个就要写一句
// services.AddTransient(); //用autofac(原理和spring差不多) 可以吧service自动注入
var builder = new ContainerBuilder();
builder.Populate(services);//Autofac.Extensions.DependencyInjection//注册服务
builder.RegisterType().As ().PropertiesAutowired();
builder.RegisterType().As ().PropertiesAutowired();
//注册所有控制器
var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
return new AutofacServiceProvider(builder.Build());
}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//在Configure里面告诉程序使用mvc中间件:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}
app.UseSwagger();app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "HelpPage V1");
});app.UseMvc();
app.UseCors("AllowCors");//cors配置 很重要 解决跨域请求的问题
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
7.新建app.config
配置你的sqlserver或者mysql 连接信息
key对应controller中using调用的配置信息
8.运行后测试一下
首先测试swagger
测试controller接口
就这样 ,后台的webapi已经搭建完成
有不足请多多指点,有问题留言,尽力 帮助
接下来会写关于前台搭建