【问题标题】:How do I configure Identity in asp net core 3.1?如何在 asp net core 3.1 中配置身份?
【发布时间】:2020-08-20 16:16:23
【问题描述】:

我正在尝试为我的 asp net core 3.1 mvc 网站进行 google 身份验证。我有身份问题。这是我收到的错误。

InvalidOperationException:尝试激活“rapLegend.Controllers.ContactController”时无法解析“Microsoft.AspNetCore.Identity.SignInManager`1[RapLegendFinal.Data.RapLegendFinalIdContext]”类型的服务。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using rapLegend.Controllers;
using Microsoft.EntityFrameworkCore;
using RapLegendFinal.Data;
using RapLegendFinal.Areas.Identity;
//using RapLegendFinal.Data;

namespace RapLegendFinal
{
    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<DbContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("RapLegendFinalIdContextConnection")));




            services.AddControllersWithViews();

            services.AddAuthentication().AddGoogle(options =>
            {

                IConfigurationSection googleAuthNSection =
                Configuration.GetSection("Authentication:Google");

                options.ClientId = "client id";
                options.ClientSecret = "client secret";

            });

        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

这是身份上下文..

namespace RapLegendFinal.Data
{
    public class RapLegendFinalIdContext : IdentityDbContext<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>
    {
        public RapLegendFinalIdContext()
        {

        }
        public RapLegendFinalIdContext(DbContextOptions<DbContext> options)
            : base(options.ToString())
        {
        }

    }
}

联系人控制器代码..

namespace rapLegend.Controllers
{
    public class ContactController : Controller
    {
        emailSuggesters newsuggester = new emailSuggesters();

         private readonly RapLegendFinalContext _context;
        private readonly SignInManager<RapLegendFinalIdContext> _signInManager;

        public ContactController(RapLegendFinalContext context, SignInManager<RapLegendFinalIdContext> signInManager)
        {
            _context = context;
            _signInManager = signInManager;
        }

        public async Task<IActionResult> Index()
        {
            await Task.Delay(100);
            return View();
        }


        [HttpPost]
        public async Task<IActionResult> Index(emailSuggesters model)
        {
            newsuggester.Name = model.Name;
            newsuggester.Email = model.Email;
            newsuggester.Message = model.Message;

             _context.emailSuggesters.Add(newsuggester);
             await _context.SaveChangesAsync();


            return View();
        }



        [HttpGet]
        public async Task<IActionResult> Authentication(string returnUrl)
        {
            newsuggester.ReturnUrl = returnUrl;
            newsuggester.ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            return View(newsuggester);
        }

        [HttpPost]
        public IActionResult ExternalLogin(string provider, string returnUrl)
        {
            var redirectUrl = Url.Action("ExternalLoginCallback", "ContactController", new { ReturnUrl = returnUrl });
            var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);

            return new ChallengeResult(provider, properties);
        }


        public async Task<IActionResult> Send(emailSuggesters model)
        {

            await Task.Delay(100);

            try
            {

                MimeMessage newmessage = new MimeMessage();

                newmessage.To.Add(new MailboxAddress("Arthur", "artulidis@gmail.com"));
                newmessage.From.Add(new MailboxAddress(model.Name, model.Email));
                newmessage.Subject = "New Song Suggestion!";
                newmessage.Body = new TextPart("plain")
                {
                    Text = model.Message
                };


                using (var gmail = new SmtpClient())
                {
                    gmail.Connect("smtp.gmail.com", 587, false);

                    gmail.Authenticate(model.Email, model.Password);


                    gmail.Send(newmessage);
                    gmail.Disconnect(true);
                }

                using (var yahoo = new SmtpClient())
                {
                    yahoo.Connect("smtp.yahoo.com", 587, false);

                    yahoo.Authenticate(model.Email, model.Password);


                    yahoo.Send(newmessage);
                    yahoo.Disconnect(true);
                }



            }
            catch (ArgumentNullException)
            {

            }

            return View();
        }


    }
}

如果需要检查此问题的任何其他代码文件,我很乐意将其包含在内。谢谢!

【问题讨论】:

  • 能否贴出ContactController的相关代码?
  • 好的.. 我用联系人控制器编辑了帖子

标签: c# asp.net-core model-view-controller


【解决方案1】:

你应该先添加asp.net核心身份服务才能使用SignInManager

services.AddDbContext<RapLegendFinalIdContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options =>
    options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<RapLegendFinalIdContext>();

并在Configure方法中添加认证中间件:

app.UseAuthentication();
app.UseAuthorization(); 

然后在你的控制器中注入SignInManager&lt;TUser&gt;

private readonly SignInManager<IdentityUser> _signInManager;

public ContactController(SignInManager<IdentityUser> signInManager)
{
        _signInManager = signInManager;
}

对于 Google 外部,您可以点击 herehere 获取文档和代码示例。

【讨论】:

  • 出于某种原因,当我执行 .AddEntityFrameworkStores 时,出现错误提示“IdentityBuilder 不包含 AddEntityFrameworkStores 的定义...”
  • 我的主要问题可能是我不能使用 AddDefaultIdentity 方法,因为我有这个错误
  • I can't use the AddDefaultIdentity method 是什么意思?
【解决方案2】:

私有只读SignInManager _signInManager;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2021-04-12
    • 2021-03-21
    • 2019-08-17
    相关资源
    最近更新 更多