天天看點

(前後端分離.net項目).Net core WebApi dapper Autofac依賴注入 前端Vue (上) 後端部分

.Net core WebApi  dapper  Autofac依賴注入  前端Vue

本項目采用  .Net core WebApi  dapper  Autofac依賴注入  前端Vue

前後端分離是主流,AutoFac的依賴注入簡單友善,Vue實作前端分離,dappper輕便快捷的資料庫架構

1. 檔案=》建立項目  選中asp.net core

(前後端分離.net項目).Net core WebApi dapper Autofac依賴注入 前端Vue (上) 後端部分
(前後端分離.net項目).Net core WebApi dapper Autofac依賴注入 前端Vue (上) 後端部分

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

{

    //使用者資訊 

    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

    {

         List<Users>  GetUsers();

    }

}

 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

    {

        List<Ranks> GetRanks();

    }

}

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<Users> GetUsers()

        {

            using (IDbConnection connection = new SqlConnection(ConfigurationManager.AppSettings["SqlserverConnString"]))

//連接配接資料庫查詢Users表

            {

                string sqlText = "select * from Users";

                List<Users> list = connection.Query<Users>(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 List<Ranks> GetRanks()

        {

            using (IDbConnection connection = new SqlConnection(ConfigurationManager.AppSettings["SqlserverConnString"]))

            {

                string sqlText = "select * from Ranks";

                List<Ranks> list = connection.Query<Ranks>(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)

        {

            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<IProductService, ProductService>();

            //用autofac(原理和spring差不多) 可以吧service自動注入

            var builder = new ContainerBuilder();

            builder.Populate(services);//Autofac.Extensions.DependencyInjection

            //注冊服務

            builder.RegisterType<RankService>().As<IRankService>().PropertiesAutowired();

            builder.RegisterType<ProductService>().As<IProductService>().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

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <appSettings>

    <!-- 資料庫連接配接資訊-->

配置你的sqlserver或者mysql 連接配接資訊

key對應controller中using調用的配置資訊

    <add key="SqlserverConnString" value ="Server=****;Database=**;Trusted_Connection=True"/>

    <add key="SqlConnString" value ="Server=**;Database=**;Trusted_Connection=True"/>

  </appSettings>

</configuration> 

8.運作後測試一下

首先測試swagger

(前後端分離.net項目).Net core WebApi dapper Autofac依賴注入 前端Vue (上) 後端部分

 測試controller接口

(前後端分離.net項目).Net core WebApi dapper Autofac依賴注入 前端Vue (上) 後端部分

就這樣 ,背景的webapi已經搭建完成

有不足請多多指點,有問題留言,盡力 幫助

接下來會寫關于前台搭建