小编Cal*_*alC的帖子

AspNetCore 2.0身份-注入RoleManager的问题

我需要为ROLES创建CRUD操作。

我收到以下错误:

“无法解析类型为'Microsoft.AspNetCore.Identity.RoleManager`的服务”

那么,我该如何注入roleManager?

我正在使用ASP Net Core 2.0 + Identity 2.2.1

类ApplicationUser

 public class ApplicationUser : IdentityUser
    {
        [Key]
        public override string Id { get; set; }
        public bool Type { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

现在在Startup.cs中

        services.AddIdentity<ApplicationUser, IdentityRole<int>>()
        .AddUserStore<UserStore<ApplicationUser, IdentityRole<int>, ApplicationDbContext, int>>()
        .AddRoleStore<RoleStore<IdentityRole<int>, ApplicationDbContext, int>>()
        .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

控制者

private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityUser> _roleManager;

public RolesController(UserManager<ApplicationUser> userManager, RoleManager<IdentityUser> roleManager)
{
    _userManager = userManager;
    _roleManager = roleManager; 
}


public IActionResult Index()
{
    return View(_roleManager.Roles);
}
Run Code Online (Sandbox Code Playgroud)

因此,我收到错误消息:“无法解析类型为'Microsoft.AspNetCore.Identity.RoleManager`的服务。

c# asp.net-core asp.net-core-identity

5
推荐指数
1
解决办法
2359
查看次数

在 .Net Core 中加载程序集时解决依赖项

我在 .net Core 中有一个项目,我需要将程序集(使用Roslyn编译)加载到沙箱中,以隔离代码执行。

我的第一个想法是使用AppDomain,但在 .net Core 中这是不可能的。因此,解决方案是使用AssemblyLoadContext

以下代码是我的程序集加载程序

public class AssemblyContext : AssemblyLoadContext
{
    public Assembly Load(Stream stream)
    {
        this.Resolving += ResolvingHandler;
        return this.LoadFromStream(stream);
    }

    public Assembly ResolvingHandler(AssemblyLoadContext context, AssemblyName assemblyName)
    {
        var assembly = context.LoadFromAssemblyName(assemblyName);
        Console.WriteLine("Resolving: " + assemblyName.FullName);
        return assembly;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是在加载Assembly 之后,没有调用Resolving方法并且没有加载依赖项,这使得我编译的代码无法正常工作。

是否有必要对调用ResolvingHandler做任何额外的步骤?或者这在 Core 中是不可能的?

c# roslyn .net-core

5
推荐指数
1
解决办法
2510
查看次数

使用 ASP.NET Core 2.0 进行用户管理

也许我错过了一些东西,但是,我阅读了大量关于使用 .NET Core 2.0 进行身份验证和授权的文档和文章,但我没有找到任何关于用户管理的内容。

我想要实现的是拥有一个管理员用户界面,可以创建用户、列出所有现有用户并将他们分配给预定义的角色和/或预定义的策略。

我尝试这样做但没有成功(我在尝试使用模型时遇到问题,例如IEnumerable<IdentityUser>关于无效构造函数:

InvalidOperationException:找不到适合类型“System.Collections.Generic.IEnumerable`1[Microsoft.AspNetCore.Identity.IdentityUser]”的构造函数。确保类型是具体的,并且为公共构造函数的所有参数注册了服务。

我无法RoleManager在任何控制器中获取。它适用于 UserManager,但不适用于 RoleManager。我加了

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

到启动,所以我教它会自动注入 DI ......

ApplicationUser 定义如下:

namespace KaraokeServices.Data
{
    public class ApplicationUser : IdentityUser
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我定义了一个 UserController 如:

namespace KaraokeServices.Controllers
{
    [Route("[controller]/[action]")]
    public class UserController : Controller
    {
        private readonly UserManager<ApplicationUser> userManager;

        public UserController(ApplicationDbContext pContext,  SignInManager<ApplicationUser> pSignInManager, ILogger<AccountController> logger)
        {
            userManager = pSignInManager.UserManager;
        }

        [HttpGet]
        public IActionResult Index()
        {
            List<ApplicationUser> users = new List<ApplicationUser>();

            users = userManager.Users.ToList();

            return View(users);
        } …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-authorization .net-core

5
推荐指数
1
解决办法
2040
查看次数

无法生成deps.json以启用迁移

我使用Asp.net核心mvc进行Web开发.我想通过Entity Framework Core .NET命令行工具启用实体框架迁移:

dotnet ef migrations add InitialDatabase
Run Code Online (Sandbox Code Playgroud)

但是发生错误: 无法生成deps.json,它可能已经生成:C:\ Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\GenerateDeps\GenerateDeps.proj

我错过了任何.NET Core配置吗?

ef-migrations entity-framework-core asp.net-core-mvc .net-core

5
推荐指数
1
解决办法
1302
查看次数

用于获取清除缓存的“版本字符串”的服务/扩展

背景

我有一个3视图利用html5离线应用程序功能的应用程序。因此,我在剃刀视图中生成了一个应用清单。该视图的简化版本可能如下所示:

CACHE MANIFEST

CACHE:
/site.min.css
/site.min.js
Run Code Online (Sandbox Code Playgroud)

为了使脱机应用程序正常运行,缓存的文件必须与应用程序中脱机页面请求的文件完全匹配。但是,我想对此清单中引用的js / css资源应用“缓存清除”版本字符串。对于HTML标记,它受的支持,ScriptTagHelper但是我没有找到任何支持纯URL的帮助程序/扩展方法(如上述清单中所要求)。

关于此帖子,我已经通过将a FileVersionProvider注入清单视图并使用以下AddFileVersionToPath()方法来解决了此问题:

CACHE MANIFEST

CACHE:
/site.min.css
/site.min.js
Run Code Online (Sandbox Code Playgroud)

但是,FileVersionProvider该类位于Microsoft.AspNetCore.Mvc.TagHelpers.Internal命名空间中,从维护的角度来看,该命名空间不足以使我充满信心。

最后,我为此实现的DI设置的实现并不完全理想(请参见下文)。我不喜欢这样的事实,我需要打电话给GetService()我并且一定要指定一个特定的MemoryCache

services.AddSingleton<FileVersionProvider>(s => 
    new FileVersionProvider(
        s.GetService<IHostingEnvironment>()?.WebRootFileProvider, 
        s.GetService<IMemoryCache>(), 
        new PathString("") ));
Run Code Online (Sandbox Code Playgroud)

是否有人以前曾要求使用版本字符串创建到js / css资源的链接?如果是这样,是否有更优雅的解决方案?

c# offline-caching asp.net-core-mvc asp.net-core asp.net-core-2.0

5
推荐指数
1
解决办法
376
查看次数

访问services中的Request头。WebApiCore ConfigureServices中的AddScoped?

我想为Request的标头中的类实例分配一个值作为单例。
我想ConfigureServicesStartup类的方法中使用.net core进行分配。
像这样:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddScoped<MyClass>(provider =>
    {
        var myClass = new MyClass();
        myClass.PropName = provider.Request.Headers["PropName"]; // I want to access Request Header here
    });
}
Run Code Online (Sandbox Code Playgroud)

如何在AddScoped方法中访问Request的标头?

request request-headers .net-core asp.net-core-webapi

5
推荐指数
1
解决办法
1588
查看次数

Set a different homepage URL in ASP.NET CORE

在ASP.NET Core项目中,我具有以下路线:

public class AboutController : Controller {

  [HttpGet("about-us")]
  public IActionResult Index() => View();

}
Run Code Online (Sandbox Code Playgroud)

如何将该URL设置为网站的默认主页?

因此,当我访问www.mydomain.com时,我会自动重定向到www.mydomain.com/about-us

这在ASP.NET Core中是否可行,还是我需要在域DNS上做到这一点?

asp.net-core

5
推荐指数
1
解决办法
1448
查看次数

使用 EF Core IdentityContext 和 DbContext 进行订单管理

我正在 ASP MVC Core 2 上创建一个电子商务网站。我继承了我的用户并继承了用于处理用户数据的IdentityUser上下文,并继承了用于处理产品和订单等的不同上下文。IdentityDbContextDbContext

现在,我想将订单或购物车链接到特定用户,但无法思考如何在订单表中引用用户,因为它们处于不同的上下文中。我还使用 EF 创建的默认 guid 作为两个表中的主键。

我应该放弃DbContext并只使用IdentityDbContext吗?这样做是否会导致身份中的异步方法和其他常见的非异步方法出现问题。

这是我的课程中的一些代码片段

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace shophe1.Models
{
    public enum Gender { Male, Female, Other}
    public class User : IdentityUser
    {
        public string FullName { get; set; }
        public Gender Gender { get; set; }
        public string ReferralID { get; set; }
        public DateTime RegistrationDateTime { get; set; }

        public string ActivationDateTime { get; set; } …
Run Code Online (Sandbox Code Playgroud)

asp.net-identity asp.net-core ef-core-2.0

5
推荐指数
1
解决办法
1325
查看次数

身份验证在 Kestrel 上失败,但在 IIS Express 上没有

我是 .net core 的新手,正在尝试一个带有登录页面的 web 应用程序,该页面使用 asp .net-core 中提供的身份验证功能。

当我创建并构建 Web 应用程序时,我使用 IISExpress 来运行它,并且身份验证功能正常工作,并允许我登录并使用 Web 应用程序上的各种操作。

我现在正在尝试从 IIExpress 更改为 Kestrel,但在登录时对用户进行身份验证时遇到了一些困难。

info: RestartTool.Controllers.AccountController[0]
  User logged in.
info: Microsoft.AspNetCore.Mvc.RedirectToActionResult[1]
  Executing RedirectResult, redirecting to /.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action RestartTool.Controllers.AccountController.Login (RestartTool) in 3330.8233ms
Run Code Online (Sandbox Code Playgroud)

因此,在使用 Kestrel 时,用户将正确“登录”,因为输入的用户名/密码是正确的。因此它意味着重定向到索引或 /。

  Request starting HTTP/1.1 GET http://localhost:59211/
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
  Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
  Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
  Executing ChallengeResult with authentication schemes ().
Run Code Online (Sandbox Code Playgroud)

但是,上面的错误信息出现在控制台中,页面最终在用户未登录的情况下重定向回登录页面。

在我的启动配置方法中,我添加了以下行,很多答案似乎都显示了修复程序,但它没有区别(因为它已经存在)

            app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

如果有用,在我的 ConfigureServices 方法中,我的设置如下:(多一点来指定密码设置) …

c# asp.net-core

5
推荐指数
1
解决办法
403
查看次数

从ASP.net Core 2中的视图访问自定义ApplicationUser属性

我扩展了ApplicationUser类,有2个额外的属性,FirstNameLastName.两个属性都在数据库中正确保留.

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(100)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100)]
    public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在关注一个简​​单的初学者示例,并且有问题的代码是由New Project with User Authentication命令生成的:

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
            </li>
        </ul>
    </form>
}
Run Code Online (Sandbox Code Playgroud)

而不是Hello @UserManager.GetUserName(User)! …

razor asp.net-identity asp.net-core

4
推荐指数
1
解决办法
2089
查看次数

使用API​​路由时,请在未经授权的情况下返回Http Response 401,而不是重定向到登录页面

我正在使用MVC和WebAPI构建一个ASP.NET Core 2.0网站,以提供对一系列微服务的访问.如果WebAPI控制器要求用户进行身份验证和授权(使用该Authorize属性),则任何未经授权或未登录的用户都会将响应作为MVC登录页面的整个HTML获取.

当未经授权的用户访问API时,我想在响应中返回HTTP状态代码401及其相关的错误消息,而不是整个HTML页面.

我已经看了一些现有的问题,并注意到他们要么引用ASP.NET MVC(例如WebApi.Owin中的SuppressDefaultHostAuthentication也禁止webapi之外的身份验证),这对ASP.NET Core 2.0没有好处.或者他们正在使用Core 1.x的hackaround,这似乎不对(ASP.Net核心MVC6重定向到未经授权时登录).

在Core 2.0中是否有适当的解决方案,任何人都知道?如果没有,任何想法如何正确实施?

作为参考,以控制器的一部分为例:

[Authorize]
[ApiVersion("1.0")]
[Produces("application/json")]
[Route("api/V{ver:apiVersion}/Organisation")]
public class OrganisationController : Controller
{
    ...

    [HttpGet]
    public async Task<IEnumerable<string>> Get()
    {
        return await _organisationService.GetAllSubdomains();
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

以及Statup.cs中的配置:

public void ConfigureServices(IServiceCollection services)
{
    ...

    // Add API version control
    services.AddApiVersioning(options =>
    {
        options.ReportApiVersions = true;
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.ErrorResponses = new DefaultErrorResponseProvider();
    });

    // Add and configure MVC services. …
Run Code Online (Sandbox Code Playgroud)

httpresponse http-status-code-401 asp.net-core-webapi asp.net-core-2.0

3
推荐指数
1
解决办法
1613
查看次数

对区域内的所有控制器应用授权过滤器

如何强制对一个区域内的所有控制器进行授权?具体来说,我想配置一个AuthorizeFilter作为Startup.ConfigureServices()方法的一部分应用于“管理”区域。

asp.net-core-mvc asp.net-core asp.net-core-2.1

2
推荐指数
1
解决办法
1050
查看次数

实体框架在更新时删除对象

我遇到一个问题,实体框架(核心)在更新时删除对象。我认为这与Automapper(将DTO资源映射到对象)有关。我有其他对象以与该对象完全相同的方式映射,并且更新工作得很好。

public async Task<IActionResult> UpdateFeedback(Guid Id, [FromBody] FeedbackResource feedbackResource)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
    //removing or else get a tracking error with EF
    feedbackResource.FeedbackType = null;
    var feedback = await feedbackRepository.GetFeedback(Id);

    if (feedback == null)
        return NotFound();

    //if I use this line to map, EF will delete the object upon save.  

    mapper.Map<FeedbackResource, Feedback>(feedbackResource, feedback);

    // if I map manually, i get no error
    //feedback.Title = feedbackResource.Title;
    //feedback.Details = feedbackResource.Details;
    //feedback.IsGoodFeedback = feedbackResource.IsGoodFeedback;
    //feedback.IsReviewed = feedbackResource.IsReviewed;
    //feedback.FeedbackTypeId = feedbackResource.FeedbackTypeId;

    //if(feedbackResource.IsReviewed){
    // …
Run Code Online (Sandbox Code Playgroud)

automapper entity-framework-core

1
推荐指数
1
解决办法
3181
查看次数