從零開始一個個人博客 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");
            });
        }
    }
}

文章是原創 轉載請注明出處


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM