zoukankan      html  css  js  c++  java
  • 从零开始一个个人博客 by asp.net core and angular(二)

    上一篇帖子讲了用了哪些技术,这个帖子就先介绍介绍api项目吧,项目就是一个普通的webapi项目,账户系统用的identity ,什么是identity呢? 其实就是官方封装好的一系列的可以用来操作数据库的类,对用户信息进行增删改查。主要牵扯的类有如下几个:

    UserManager

    SignInManager

    RoleManager

    上面列出的是我项目牵扯的大家有兴趣的可以去官方接口文档那里看看api

    namespace Microsoft.AspNetCore.Identity这个是命名空间

    具体的看下面的项目结构图

    大家可以把我项目给克隆下来 然后打开看看具体的配置

    api项目地址GitHub链接

    这个account控制器里面写好了创建用户的一些方法主要就是用了 UserManager 和SignInManager进行用户的创建和用户的登录

    请你跟我这样做 项目刚克隆下来是运行不起来的,因为数据使用的是PostgreSql所以首先安装PostgreSql下面是linux下的安装 如果你是本地window调试,所以再找个window版的安装教程吧 我就不细讲了

    Windows上PostgreSQL安装配置教程

    下面是安装后要做的一些操作请结合帖子进行操作 不懂的请网络找找

    实在不实行就留言吧 下图是安装后的文件目录 里面有很多的指令 下面的指令也在里面

    初始化命令

    .initdb.exe -D ..data -E UTF-8 --locale=chs -U postgres -W

    启动数据库

    .pg_ctl.exe -D ..data start

    注册服务 注册完就能开机自启了

    .pg_ctl.exe register -N PostgreSQL -D ../data

    CentOS7下PostgreSQL 11的安装和配置教程

    到时候可以用图上的软件连接测试下免费的而且用起来很不错:

    配置好数据库密码测试完成就照着我图上的操作点击管理用户机密会弹出一个json文件名字是secrets你把自己的本地测试环境的连接字符串就放到这个里面具体使用办法请看下面的帖子,此法是为了测试项目时泄露机密到github 这样操作时可以将github上的数据暴露不会泄露到时候只需修改secrets.json不需要修改appsetting.json了:

    安全存储中 ASP.NET Core 中开发的应用程序机密

    数据库如果调通了就可以运行项目了 由于大家都是新的数据库 数据库里对应的表都不存在所以需要进行数据库的更新 我这个项目主要有两个数据上下文如图到时候在DataAccess项目里执行如下指令

    Update-Database -Context BlogSysContext

    Update-Database -Context AppIdentityDbContext

    数据上下文如图到时候在DataAccess项目里执行如下指令

    我因为数据库已经更新到最新了 所以提示我已经更新了 大家可以自行试试 等到数据库表都更新好了 就可以启动项目了,项目依赖的东西都在配置文件里,大家记得好好看看。

    为什么用postgreSql是因为这个orm连接的东西更新的比较快 应该时微软有官方的人参加维护 特别适合个人和一些使用免费数据库的人使用

    Npgsql.EntityFrameworkCore.PostgreSQL这个是安装的连接器 大家到时候留意下

    保险起见 我还是把最重要的配置代码贴出来 git项目也有

    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using GreenShade.Blog.Api.Filters;
    using GreenShade.Blog.Api.Hubs;
    using GreenShade.Blog.Api.Services;
    using GreenShade.Blog.DataAccess.Data;
    using GreenShade.Blog.DataAccess.Services;
    using GreenShade.Blog.Domain.Models;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.HttpOverrides;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.IdentityModel.Tokens;
    
    namespace GreenShade.Blog.Api
    {
        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.Configure<ForwardedHeadersOptions>(options =>
                {
                    options.KnownProxies.Add(IPAddress.Parse("10.0.0.100"));
                });
                services.AddDbContext<AppIdentityDbContext>(options =>
                options.UseNpgsql(Configuration.GetConnectionString("OffLineNpgSqlCon")));
                services.AddDbContext<BlogSysContext>(options =>
                options.UseNpgsql(Configuration.GetConnectionString("OffLineNpgSqlCon")));
                services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<AppIdentityDbContext>();
                services.AddSignalR();
                services.Configure<JwtSeetings>(Configuration.GetSection("JwtSeetings"));
                services.Configure<QQLoginSetting>(Configuration.GetSection("qqlogin"));
                services.Configure<Dictionary<string, WnsSetting>>(Configuration.GetSection("wns"));
                services.AddHttpClient<ThirdLoginService>();
                services.AddScoped<ArticleService>();
                services.AddScoped<BlogManageService>();
                services.AddHttpClient<WallpaperService>();
                services.AddHttpClient<PushWnsService>();
                //services.AddScoped<ThirdLoginService>();
                var jwtSeetings = new JwtSeetings();
                //绑定jwtSeetings
                Configuration.Bind("JwtSeetings", jwtSeetings);
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = jwtSeetings.Issuer,
                        ValidAudience = jwtSeetings.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSeetings.SecretKey))
                    };
                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = context =>
                        {
                            var accessToken = context.Request.Query["access_token"];
    
                            if (!string.IsNullOrEmpty(accessToken) &&
                                (context.HttpContext.WebSockets.IsWebSocketRequest || context.Request.Headers["Accept"] == "text/event-stream"))
                            {
                                context.Token = context.Request.Query["access_token"];
                            }
                            return Task.CompletedTask;
                        }
                    };
                });
                services.AddCors(options =>
                {
                    options.AddPolicy("any", builder =>
                    {
                        builder.AllowAnyOrigin() //允许任何来源的主机访问
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .WithOrigins("http://192.168.1.109:4200", "http://localhost:4200", "http://192.168.1.103:4200",
                        "http://192.168.1.103:4200", "http://192.168.16.67:4200", "http://192.168.16.138:4200", "https://www.douwp.club")
                        .AllowCredentials()//指定处理cookie
                        .SetPreflightMaxAge(TimeSpan.FromSeconds(60));
                    });
                });
                services.AddControllers(options =>
                {
                    options.Filters.Add(new ExceptionHandleAttribute());//根据实例注入过滤器
                });
                //services.AddControllers();
            }
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
                });
    
                app.UseCors("any");
                app.UseWebSockets();
                app.UseRouting();
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapHub<ChatHub>("/chathub");
                });
            }
        }
    }
    
    

    文章是原创 转载请注明出处

  • 相关阅读:
    BZOJ1077 并查集
    linux(fedora) 第三课
    hdu 4513 吉哥系列故事——完美队形II(manacher)
    hdu 3294 Girls' research(manacher)
    FZU
    蓝桥杯试题 k倍区间(dp)
    蓝桥杯 带分数(全排列+枚举)
    天梯赛 L2-001 紧急救援
    蓝桥杯[2017年第八届真题]分考场 (图着色问题)
    hdu 3068 最长回文(manacher)
  • 原文地址:https://www.cnblogs.com/GreenShade/p/12234637.html
Copyright © 2011-2022 走看看