• .net Core 1.0.1 下的Web框架的的搭建过程step by step


    环境:ubuntu+VScode  数据库:mysql ,ORM框架:chloe 官网

    看完本篇文章你能学会 在Vscode下创建项目,一些基础的命令 ,以及得到一个配置文件的简单读取实例

    1,在VScode下安装插件:C# 和 NuGet PackageManager

    2,打开终端执行项目的创建: 

    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ mkdir Model
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ mkdir Bll
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ mkdir Web
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ cd Model
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2/Model$ dotnet new ClassLib
    Content generation time: 30.2507 ms
    The template "Class library" created successfully.
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2/Model$ cd ../Bll
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2/Bll$ dotnet new ClassLib
    Content generation time: 27.063 ms
    The template "Class library" created successfully.
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2/Bll$ cd ../Web
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2/Web$ dotnet new mvc
    Content generation time: 317.1098 ms
    The template "ASP.NET Core Web App" created successfully.
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2/Web$ cd ../
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ dotnet new sln
    Content generation time: 28.6445 ms
    The template "Solution File" created successfully.
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ dotnet sln test2.sln add Bll/Bll.csproj
    Project `Bll/Bll.csproj` added to the solution.
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ dotnet sln test2.sln add Model/Model.csproj
    Project `Model/Model.csproj` added to the solution.
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ dotnet sln test2.sln add Web/Web.csproj
    Project `Web/Web.csproj` added to the solution.
    siecan@siecan-Lenovo-H3050:~/dotnetproject/test2$ dotnet add Bll/Bll.csproj reference Model/Model.csproj

    注:通过命令:dotnet sln test2.sln add Bll/Bll.csproj 将bll添加到解决方案 下同,
    add Bll/Bll.csproj reference Model/Model.csproj 给Bll添加model的引用


    修改Bll.csproj中 <TargetFramework>节点的值为:netcoreapp1.1

    在新打开的vscode上单独打开bll 【相关的类库没有做类库的兼容导致的问题,后期可能就不需要这么麻烦在解决方案下就可以添加】  
    使用nuget方式给Bll添加引用 MySql.Data 和 ChloeCore.Mysql 和ChloeCore
    操作方式:在VScode界面按F1 输入nuget 回车 输入 mysql 回车 选择mysql.data 回车,选择最新版本回车,
    ChloeCore.mysql同上

    执行完毕后在bll.csproj中会多出如下内容: 也可以手动添加内容到Bll.csproj

     <ItemGroup>
        <PackageReference Include="MySql.Data" Version="7.0.7-m61"/>
        <PackageReference Include="ChloeCore.MySql" Version="2.5.0"/>
      </ItemGroup>

    读取配置文件需要用到 Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json 添加方式同上 nuget方式

    当前Bll.csproj的内容如下:

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <Project Sdk="Microsoft.NET.Sdk">
       <ItemGroup>
        <ProjectReference Include="..ModelModel.csproj" />
      </ItemGroup>
    
      <ItemGroup>
        <PackageReference Include="ChloeCore.MySql" Version="2.5.0" />
        <PackageReference Include="MySql.Data" Version="7.0.7-m61" /> 
        <PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.1" />
        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
      </ItemGroup>
      <PropertyGroup>
        <TargetFramework>netcoreapp1.1</TargetFramework>
      </PropertyGroup>
    </Project>

    bll中添加数据上下文类:

    DbContext:  

    using System.IO;
    using Chloe.MySql;
    using Microsoft.Extensions.Configuration;
    
    namespace Bll
    {
        public class DataContent
        {
            static MySqlContext ctx = null;
            public static MySqlContext Context()
            {
                if (DataContent.ctx == null)
                {
                    IConfigurationRoot Configuration;
                    ConfigurationBuilder Builder=new ConfigurationBuilder();
                    Builder.SetBasePath(Directory.GetCurrentDirectory());
                    Builder.AddJsonFile("appsettings.json");
                    Configuration =Builder.Build();
                    string ConnectionStr =Configuration.GetConnectionString("MySqlConnectionString");
                    MySqlConnectionFactory factory = new MySqlConnectionFactory(ConnectionStr);
                    DataContent.ctx = new MySqlContext(factory);
                }
                return DataContent.ctx;
            }
        }
    }
    MySqlConnectionFactory:参考 http://www.52chloe.com
    using System;
    using System.Data;
    using Chloe;
    using Chloe.MySql;
    using MySql.Data.MySqlClient;
    namespace Bll
    {
        public class MySqlConnectionFactory : Chloe.Infrastructure.IDbConnectionFactory
        {
            string _connString = null;
            public MySqlConnectionFactory(string connString)
            {
                this._connString = connString;
            }
            public IDbConnection CreateConnection()
            {
                MySqlConnection conn = new MySqlConnection(this._connString);
                return conn;
            }
        }
    }

    测试类Person:

    using System;
    using System.Collections.Generic;
    
    namespace Bll
    {
        public class Person
        {
            public List<Model.Person> GetAllPerson()
            {
                return DataContent.Context().Query<Model.Person>().ToList();
            }
            public int AddPerson()
            {
                Random r=new Random(100);
                Model.Person p=new Model.Person(Guid.NewGuid().ToString(),r.Next(),Guid.NewGuid().ToString(),Guid.NewGuid().ToString());
                Model.Person presult = DataContent.Context().Insert<Model.Person>(p);
                return presult.id;
            }
            public int DelPerson(int id)
            {
                return DataContent.Context().Delete<Model.Person>((x)=>x.id==id);
            }
        }
    }

     Model中添加Person实体类:

    namespace Model
    {
        public class Person
        {
            public Person(string name,int age,string username,string password)
            {
                this.Name=name;
                this.Age=age;
                this.UserName=username;
                this.PassWord=password;
            }
            public Person(){}
            public int id {get;set;}
            public string Name{get;set;}
            public int Age{get;set;}
            public string UserName{get;set;}
            public string PassWord{get;set;}
        }
    }
    View Code

    在Web文件夹中找到appsettings.json,添加数据库连接语句:

      
    "ConnectionStrings":{
        "MySqlConnectionString":"Database=Test;Data Source=localhost;User Id=root;Password=123;pooling=false;CharSet=utf8;port=3306"
      }

    appsettings.json最终结构如下:

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "ConnectionStrings":{
        "MySqlConnectionString":"Database=Test;Data Source=localhost;User Id=root;Password=123;pooling=false;CharSet=utf8;port=3306"
      }
    }

    在homecontroller中 添加测试代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Bll;
    
    namespace Web.Controllers
    {
        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                Bll.Person p= new Bll.Person();
                List<Model.Person> lst = p.GetAllPerson();
                ViewBag.lst=lst;
                return View();
            }
            [HttpPost]
            public int DelTestData(int id)
            {
                 Bll.Person p=new Bll.Person();
                 return p.DelPerson(id);
            }
            [HttpPost]
            public int AddTestData()
            {
                Bll.Person p=new Bll.Person();
                 return p.AddPerson();
            }
            public IActionResult Error()
            {
                return View();
            }
        }
    }

    在添加视图前有个坑,.netcore项目在调试的时候看不到样式效果,使用F1->nuget也无法把所需要的css和javascript添加到项目中 ,无奈。 心情烦躁之际在终端写下 sudo apt-get install nuget。敲了个回车居然可以安装,暗爽了一把,等执行完毕以后,打开到web目录执行nuget install bootstrap 。奇迹发生了,需要的文件居然添加到项目中了。

    然后把母版页中的那些引用改成自己的路径, 这里还有一坑  静态文件是不能放到根目录下的,不然会找不到,必须放到静态文件目录 默认是wwwroot目录,这时才能通过~/... 路径来定位到对应的CSS和javascript

    来张项目结构图压压惊

    视图:Index.cshtml

    @{
        ViewData["Title"] = "Home Page";
    }
    <script type="text/javascript">
        $(document).ready(function(){
            $("#btnAddtest").click(function(){
                $.ajax({
                    url:"AddTestData",
                    data:{},
                    type:"Post",
                    success:function(obj){
                        if(obj>0){
                            location.reload();
                        }
                    }
                }) ;
            });
            $("[Name='del']").click(function(){
                $.ajax({
                    url:"DelTestData",
                    data:{"Id":this.id},
                    type:"Post",
                    success:function(obj){
                        if(obj>0)
                        {
                            location.reload();
                        }
                    }
                })
            });
        });
    </script>
    @using Model;
    <button id="btnAddtest">添加测试数据</button>
    用户列表:
    <table class="table table-bordered table-hover">
        <tr>
            <th>名称</th>
            <th>年龄</th>
            <th>用户名</th>
            <th>密码</th>
            <th>操作</th>
        </tr>
    @foreach(Person s in @ViewBag.lst as List<Person>)
    {
        <tr>
            <td>@s.Name</td>
            <td>@s.Age</td>
            <td>@s.UserName</td>
            <td>@s.PassWord</td>
            <td>
            <button type="button" class="btn btn-large btn-block btn-default" name="del" id="@s.id">删除</button>
            </td>
        </tr>
    }
    </table>

    前台写的非常简单,请打开完整路径查看效果  localhost:5000/Home/index

    基本结束了,最后再附一张运行效果图

    有问题请留言,欢迎讨论学习

  • 相关阅读:
    手游营销的10个靠谱方向
    创业三个月总结---记录这三个月的酸甜苦辣咸!!!
    创业三个月总结---记录这三个月的酸甜苦辣咸!!!
    Notepad++ 删除空白行的方法
    Notepad++ 删除空白行的方法
    几种常见容器比较和分析 hashmap, map, vector, list ...hash table
    hdu 3371
    hdu 1879
    hdu 1875
    hdu 1863
  • 原文地址:https://www.cnblogs.com/zzfstudy/p/6610371.html
Copyright © 2020-2023  润新知