tnblog
首页
视频
资源
登录

identityServer4 退出登录+EF

7034人阅读 2019/12/20 10:59 总访问:97709 评论:0 收藏:0 手机
分类: Net Core

登录讲完了 我们讲一下退出登录


退出比较简单啦

 [HttpGet]
        public async Task<IActionResult> Logout(string logoutId)
        {
            var logout = await _interaction.GetLogoutContextAsync(logoutId);
            await HttpContext.SignOutAsync();
            //获取客户端点击注销登录的地址
            var refererUrl = Request.Headers["Referer"].ToString();
             if (!string.IsNullOrWhiteSpace(refererUrl))
            {
                return Redirect(refererUrl);
            }
            else
            {
                //获取配置的默认的注销登录后的跳转地址
                if (logout.PostLogoutRedirectUri != null)
                {
                    return Redirect(logout.PostLogoutRedirectUri);
                }
            }
            return View();

        }

我们在写一个方法就好 

  public IActionResult logout()
        {
            return SignOut("Cookies", "oidc");
        }

下面我们讲一下 Net Core 使用EF


这里 我们电脑的版本可能一样 这里给几个下包

一.使用Nuget添加EF的依赖


输入命令:  Install-Package Microsoft.EntityFrameworkCore.SqlServer

安装成功后就可以在依赖项中看到

注意执行命令的项目你可能需要选择一下


 三.如果是使用db first,需要根据数据库生成model,就还需要使用命令添加两个依赖


Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design


安装成功后就可以在依赖项中看到



四.相关依赖添加成功后,就可以更具一个命令就可以从数据库生成model了  

 

命令:    Scaffold-DbContext "Server=.;Database=数据库名;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models


注意:有可能执行这个命令会报错:

 1:执行这一步的时候出现了点问题 ,因为系统是win7,powershell版本太低了,不支持这个命令,需要安装

3.0以上的powershell版本才行      


2: Could not load assembly 'DAL'. Ensure it is referenced by the startup project 'xxxx'.

是因为主项目没有添加到这个DAL层的引用,添加了就行了,所以估计执行这个命令会使用到启动项目的一些东西


3:Your startup project 'xxxxx' doesn't reference Microsoft.EntityFrameworkCore.Design.This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

他是说你启动项目没有这个依赖,在启动项目里边执行一下这个两个命令就好了

Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

好像执行执行那个.Tools也可以,我就奇怪了nuget执行的明明不是启动项目为什么启动项目中还要添加这个依赖呢,

只在启动项目添加这个依赖行不行呢


如果model已经生成过了,想全部覆盖的话,可以在后面加一个-force命令:

Scaffold-DbContext "Server=.;Database=Food;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force


更新某个表:后面加-tables 表名

 Scaffold-DbContext "Server=.;Database=Food;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -tables Article

但是更新某个表有坑啊,如果覆盖了,那个表不会生成导航属性,而且那个山下文对象也只有那个表的内容了....暂时没有找到更好的办法...

单独更新拷贝过来,或者全部更新,或者直接写手吧,比如添加了一个字段什么的


     

 添加成功后在models可以看到, 生成了上下文对象与和表对应的model


官方文档

https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/cli/powershell



然后就可以开始使用EF了

 public IActionResult Index()        {             FoodContext fc = new FoodContext();             List<ProType> ptlist = fc.ProType.ToList();             ViewBag.ptlist = ptlist;             return View();        }



五.使用依赖注入来装载EF的上下文对象


 .net core中用了不少的依赖注入,官方文档中也推荐使用


1:删除方法     

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)        {            //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.            optionsBuilder.UseSqlServer(@"Server=.;Database=Food;Trusted_Connection=True;");        }


2:添加方法 

     public FoodContext(DbContextOptions<FoodContext> options)            : base(options)        {         }

添加的是一个构造函数用于构造函数注入(这个方法在新版的时候会自动加入)



3:在startup.cs的ConfigureServices方法中添加依赖注入    

  public void ConfigureServices(IServiceCollection services)        {            // Add framework services.            services.AddMvc();             services.AddDbContext<FoodContext>(option => {                option.UseSqlServer("Data Source =.; Initial Catalog = EFCore_dbfirst; User ID = sa; Password = sa.123");            });                    }

注:usersqlserver是一个扩展方法,需要添加ef core的引用using Microsoft.EntityFrameworkCore;       


  • 连接字符串写入配置文件

      http://www.tnblog.net/aojiancc2/article/details/1266  



4:使用的时候就不能直接去实例化了否则会报错找不到上下文对象

应该使用注入的方式去获取ef对象,例如构造函数注入

  private CNBlog_ServerContext ef;        public ArticleDAL(CNBlog_ServerContext context) //通过依赖注入得到实例        {            ef = context;        }




 微软官方文档:

 https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db 


下面就是我们的代码了

想要标准,高大上一点的话 我们就不直接new了

我们用依赖注入来做


一,先创建一个DAL

  public Userinfo Loging(string name, string pwd)
        {
            
                Userinfo userinfo = _fakedbContext.Userinfo.Where(a => a.Name == name && a.Pwd == pwd).FirstOrDefault();
                return userinfo;
        }

写标准一点 我们在这创2个文件夹

二,然后在Startup中配置好依赖注入关系

三,然后我们添加刚才配置好的依赖

   //依赖注入
        private readonly IIdentityServerInteractionService _interaction;
        private readonly IUserDAL _userDAL;
        public AccountController(IIdentityServerInteractionService interaction, IUserDAL userDAL)
        {
            _interaction = interaction;
            _userDAL = userDAL;
        }

最后一步我们就可以调用了

[HttpPost]
        public async Task<IActionResult> Login(string userName, string password, string returnUrl = null)
        {
            ViewData["returnUrl"] = returnUrl;
            ViewBag.username1 = userName;
            Userinfo userinfo=  _userDAL.Loging(userName, password);
            if (userinfo != null)
            {
                AuthenticationProperties props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1)),
                };
                //注意这里应该引用Microsoft.AspNetCore.Http这个下面的
                await HttpContext.SignInAsync("10000", userName, props);
                //HttpContext.SignOutAsync();
                if (returnUrl != null)
                {
                    return RedirectToLocal(returnUrl);
                    //return Redirect("http://localhost:44396/home/index");
                }
                return View();
            }
            else
            {
                return Content("登录失败");
            }
         }
         
     这样我们就搞定啦


评价
最近老犯困
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术