从零搭建DotnetCore2.0

右键解决方案>新建项目>

选择Web>ASP.NETCoreWeb应用程序(.NET Core)

选择Web应用程序,暂时不选择启用Docker,身份验证选择个人用户账户(会自动生成一系列和用户认证的代码)

随后生代码层次目录如下:

其中会包含身份信息的相关实现,比如相关实体信息(user)之类的,如果想对扩展微软自动的生成的用户实体类,可在Models中的ApplicationUser下扩展,

在此ApplicationUser中添加属性即可:比如添加叫WeChatId属性,添加后如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace DotNetCore20.Web.Models
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        /// <summary>
        /// 微信Id
        /// </summary>
        public string WeChatId { get; set; }
    }
}

生成运行,数据库的AspNetUsers中就会多出WeChatId 属性.

一:安装引用

nugnet恢复引用失效时,可在程序包管理控制台输入:

dotnet restore  即可

会发现在恢复指令后在NuGet中会有一个Microsoft.VisualStudio.Web.CodeGeneration.Design的报错,信息如下:

已使用“.NETPortable,Version=v0.0,Profile=Profile259, .NETFramework,Version=v4.6.1”而不是项目目标框架“.NETCoreApp,Version=v2.0”还原了包“Microsoft.Composition 1.0.27”。这可能会导致兼容性问题

这个库是ASP.NET Core的代码生成工具。包含用于生成控制器和视图的dotnet-aspnet-codegenerator命令,暂时可先卸载,不影响项目运行.

对项目类库的引用三种两种方式

1.Nuget去安装(官网https://www.nuget.org/packages/)

2.右键依赖项点击菜单中的添加引用

3.可在程序包管理控制台输入:

Install-Package 

引用类库名称 版本

二.创建实体程序集

右键解决方案>添加项目>

 

首先创建抽象类,供Entity实体继承,主要为每个实体提供公用属性

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text;

namespace DotNetCore20.Entity.Core
{
    /// <summary>
    /// DB表基底
    /// </summary>
    [Serializable]
    public abstract partial class BaseEntity
    {
        /// <summary>
        /// Id
        /// </summary>
        [DataMember]
        public long Id { get; set; }

        /// <summary>
        /// DB 資料版號
        /// </summary>
        [Timestamp]
        public byte[] RowVersion { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        [DataMember]
        public DateTime CreateTime { get; set; }

        /// <summary>
        /// 更新时间
        /// </summary>
        [DataMember]
        public DateTime UpdateTime { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        [DataMember]
        public EnumState State { get; set; }
    }

    /// <summary>
    /// 状态
    /// </summary>
    public enum EnumState
    {
        /// <summary>
        /// 删除
        /// </summary>
        Delete = 1,

        /// <summary>
        /// 正常
        /// </summary>
        Normal = 0,
    }
}

添加一个UserExtend用户扩展类(Entity):

using DotNetCore20.Entity.Core;
using System;
using System.Runtime.Serialization;

namespace DotNetCore20.Entity
{
    [DataContract]
    public class UserExtend : BaseEntity
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        [DataMember]
        public long UserId { get; set; }

        /// <summary>
        /// 昵称
        /// </summary>
        [DataMember]
        public long NickName { get; set; }

    }
}

三.创建数据层

添加引用

DAL层需要用到EF实体映射相关和我们自己前面定义的Entity中的UserExtend实体表,所以要添加相关引用,DotNetCore20.Entity和  Microsoft.EntityFrameworkCore.Tools

快捷键:Ctrl+Alt+o 打开程序包管理器输入以下:

install-package Microsoft.EntityFrameworkCore.Tools

如果是网络限制下载失败,推荐把nuget镜像改为博客园资源,方法如下:

右键解决方案>管理解决方案的nuget程序包.显示如下:

新建一个数据上下文类,目录结构如下:

DotNetCoreDbContext内部代码改为以下:

using DotNetCore20.Entity;
using Microsoft.EntityFrameworkCore;

namespace DotNetCore20.DAL.DbContext
{
    public class DotNetCoreDbContext : Microsoft.EntityFrameworkCore.DbContext
    {
        public DotNetCoreDbContext(DbContextOptions<DotNetCoreDbContext> options) : base(options)
        {
        }
        public DbSet<UserExtend> UserExtend { get; set; }
    }
}

在此基本的实体映射相关的代码都完毕,现在还有一步,就是数据库连接字符串的配置

首先打开appsettings.json文件,在ConnectionStrings节点下增加以下

"DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"

增加后如下:

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDefaultDb;Trusted_Connection=True;MultipleActiveResultSets=true",
        "DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

再打开web网站下的Startup文件,在ConfigureServices方法中添加一下行:

//自定义数据库连接字符串
            services.AddDbContext<DotNetCoreDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection")));

增加后如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using DotNetCore20.Web.Data;
using DotNetCore20.Web.Models;
using DotNetCore20.Web.Services;
using DotNetCore20.DAL.DbContext;

namespace DotNetCore20.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //自定义数据库连接字符串
            services.AddDbContext<DotNetCoreDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

运行程序,点击登陆(只要访问数据库的操作都可),出现错误页面:

点击应用迁移,即自动迁移数据库.

由于两个数据库,只会自动迁移关于用户的表AspNetUsers,

所以还得VS中程序包管理器中下命令迁移.

Add-Migration firstMigration -DotNetCoreDbContext

Update-Database;

运行即可

时间: 2024-08-11 09:42:21

从零搭建DotnetCore2.0的相关文章

微服务之:从零搭建ocelot网关和consul集群

原文:微服务之:从零搭建ocelot网关和consul集群 介绍 微服务中有关键的几项技术,其中网关和服务服务发现,服务注册相辅相成. 首先解释几个本次教程中需要的术语 网关 Gateway(API GW / API 网关),顾名思义,是企业 IT 在系统边界上提供给外部访问内部接口服务的统一入口,简化了外部由于多服务协同完成任务时的繁琐配置.网关组件有Kong,ocelot, 服务发现:通过网关访问内部各个微服务,网关要找到所需服务的过程称为服务发现 服务注册:既然有服务发现,前提是要把所需服

从零搭建springboot+mybatis逆向工程

一.从零搭建springboot+mybatis逆向工程 1.新建项目 2.next到这里要勾选这两项 第一次有点慢,等一会儿就好 3.在pom.xml中添加mybatis-generator插件 只把图片中的复制到项目中即可 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q

使用Owin中间件搭建OAuth2.0认证授权服务器

前言 这里主要总结下本人最近半个月关于搭建OAuth2.0服务器工作的经验.至于为何需要OAuth2.0.为何是Owin.什么是Owin等问题,不再赘述.我假定读者是使用Asp.Net,并需要搭建OAuth2.0服务器,对于涉及的Asp.Net Identity(Claims Based Authentication).Owin.OAuth2.0等知识点已有基本了解.若不了解,请先参考以下文章: MVC5 - ASP.NET Identity登录原理 - Claims-based认证和OWIN

[dotnetCore2.0]学习笔记之一: ASP.NET Core 升级到2.0

需要升级: 1.SDK2.0 ,需要单独安装:https://www.microsoft.com/net/core#windowscmd VS2017 不包含这个SDK:而这个SDK包含了runtime,所以不需要单独安装Runtime包了: 2.升级VS 2017 到15.3+:最初是从15.2升级的,发现各种问题(比如@page不识别.Razor Page等有问题)后来重新更新了一下与Asp.net Core 的安装:后来就正常了:估计是以前安装了很多Privew版本,卸载的时候误伤了什么吧

Ubuntu12.04搭建Tomcat7.0

1.安装JAVA环境 apt-get update apt-get install openjdk-7-jdk 2.配置JAVA环境变量:vim /etc/environment JAVA_HOME=JDK目录(一般在=/usr/lib/jvm/jdk1.7.0_04/)CLASSPATH=.:/usr/lib/jvm/jdk1.7.0_04/lib 3.获取Tomcat安装包官方下载一个解压即可,下载地址:http://mirrors.cnnic.cn/apache/tomcat/tomcat

Mac下搭建hexo3.0博客

Mac下搭建hexo3.0博客(文章同步自个人博客网站以及Github博客https://xingstarx.github.io/) window环境下搭建hexo博客 具体内容可以参考这一篇文章如何搭建一个独立博客--简明Github Pages与Hexo教程本人博客搭建过程也是参考了上面的部分内容. 安装Node.js和git 安装Node.js 到Node.js网站上下载后缀为pkg的文件,点击安装. 在终端下输入 node -v npm -v 若无错,则显示版本号 本人的信息如下: he

Aix6.1搭建tomcat7.0.57步骤

Aix6.1搭建tomcat7.0.57步骤: 1.确认有java6 bill_ah1:/usr/java6/bin#java -version java version "1.6.0" Java(TM) SE Runtime Environment (build pap3260sr9fp2-20110627_03(SR9 FP2)) IBM J9 VM (build 2.4, JRE 1.6.0 IBM J9 2.4 AIX ppc-32 jvmap3260sr9-20110624_

CentOS7搭建ELK6.0.1

CentOS7搭建ELK6.0.11.准备工作:源码包路径:/usr/local/src/elasticsearch: elasticsearch-6.0.1.tar.gzkibana: kibana-6.0.1-linux-x86_64.tar.gzlogstash: logstash-6.0.1.tar.gzjdk: jdk-8u65-linux-x64.gz 2.安装java环境 cd /usr/local/src tar zxf jdk-8u65-linux-x64.gz -C /usr

Centos7搭建redis5.0.5集群

Centos7搭建redis5.0.5集群 发表于 2019-09-06 | 分类于 Linux, Redis Redis是一个开源(BSD许可),内存数据结构存储,用作数据库,缓存和消息代理.它支持数据结构,如字符串,散列,列表,集合,带有范围查询的排序集,位图,超级日志,具有半径查询和流的地理空间索引.Redis具有内置复制,Lua脚本,LRU驱逐,事务和不同级别的磁盘持久性,并通过Redis Sentinel提供高可用性并使用Redis Cluster自动分区. 官网地址 一.集群方案比较