小编Cal*_*alC的帖子

实体框架核心迁移 - 连接字符串

我在处理数据库连接字符串和迁移时遇到问题.我有2个项目:

  • 应用

DbContext是在域项目,所以这是我对运行迁移项目.迁移概念强制我OnConfiguring在我DbContext和其中指定数据库提供程序,例如:

protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
    builder.UseSqlServer("<connection string>");
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我不想使用硬编码连接字符串,原因很明显,我不能使用ConfigurationManager从配置文件中读取它,因为配置文件在应用程序项目中.

c# ef-migrations entity-framework-core .net-core

18
推荐指数
4
解决办法
6795
查看次数

ASP.NET Core 2.0中的多个身份

我正在将ASP.NET Core 1.0应用程序迁移到ASP.NET Core 2.0.

在我的启动中,我正在配置两个身份:

services.AddIdentity<IdentityUser, IdentityRole>(configureIdentity)
   .AddDefaultTokenProviders()
   .AddUserStore<IdentityUserStore<IdentityUser>>()
   .AddRoleStore<IdentityRoleStore<IdentityRole>>();

services.AddIdentity<Customer, CustomerRole>(configureIdentity)
   .AddDefaultTokenProviders()
   .AddErrorDescriber<CustomerIdentityErrorDescriber>()
   .AddUserStore<CustomerStore<Customer>>()
   .AddRoleStore<CustomerRoleStore<CustomerRole>>();
Run Code Online (Sandbox Code Playgroud)

这在ASP.NET Core 1.0中运行良好,但失败并出现错误:System.InvalidOperationException:' ASP.NET 已存在:Identity.Application'在ASP.NET Core 2.0中.

在ASP.NET Core 2.0中,如果我删除其中一个对AddIdentity错误的调用就会消失.如何迁移我的代码,以便在我的应用程序中使用两种不同类型的身份用户和角色?或者,当我在ASP.NET Core 1.0中编写此内容时,我是否只是在理解事情如何工作方面犯了一个根本错误?

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

11
推荐指数
2
解决办法
5095
查看次数

控制器不在mvc 4中工作

我有一个名为UserController的控制器,并且只调用了Index操作,添加了另外一个操作,例如' home action '没有被调用,并且调用了actionresult/string或者返回视图

我收到了这个错误

在谷歌浏览器上运行时

{"消息":"找不到与请求URI匹配的HTTP资源URI /user/home'.","MessageDetail":"找不到与名为'home'的控制器匹配的类型."}

并在Mozilla Firefox上运行

哎呦!找不到该页面.试着再给它一次机会.

这是我的整个控制器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc4Application1.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AddPlace()
        {
            return View();
        }

        public ActionResult UpdatePlace()
        {
            return View();
        }

        public ActionResult DeletePlace()
        {
            return View();
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

这是RouteConfig.cs文件

 routes.MapRoute(
     name: "Default",
      url: "{controller}/{action}/{id}",
 defaults: new 
{ controller = "Home", action = …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

10
推荐指数
3
解决办法
2万
查看次数

获取所有设置的Asp.Net Core 2.0中的Configuration.GetSection

我正在尝试学习检索配置信息的各种方法,以便我可以确定为即将开始的项目设置和使用配置的最佳途径.

我可以使用访问各种单一设置

var sm = new SmsSettings
    {
        FromPhone = Configuration.GetValue<string>("SmsSettings:FromPhone"),               
        StartMessagePart = Configuration.GetValue<string>("SmsSettings:StartMessagePart"),               
        EndMessagePart = Configuration.GetValue<string>("SmsSettings:EndMessagePart")
    };
Run Code Online (Sandbox Code Playgroud)

我还需要能够计算设置,确定某些设置的值等.所以我正在构建一个解析方法来执行这些类型的事情,并且需要设置文件的整个部分,这就是我假设的GetSection所做的.错误.

appsettings文件

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo;Trusted_Connection=True;MultipleActiveResultSets=true",
  "ProductionConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Production;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Warning"
  }
},   
"SmsSettings": {
  "FromPhone": "9145670987",      
  "StartMessagePart": "Dear user, You have requested info from us on starting",      
  "EndMessagePart": "Thank you."
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是两个截图

var section = Configuration.GetSection("ConnectionStrings");
Run Code Online (Sandbox Code Playgroud)

回报

图1:变量属性

图2:深入研究JsonConfigurationProvider

出现了一些问题.

  1. 为什么这会返回3个不同的JsonConfigurationProviders,其中一个包含appsettings.json文件中的每个设置(如图2所示)
  2. 为什么GetSection("ConnectionStrings")不能实现这一点,返回ConnectionStrings的子子元素
  3. 给定数字2,你如何实际检索ConnectionStrings的子项?
  4. 假设模型ConnectionStrings具有一个属性List Connections,该部分可以转换为对象吗?

configuration asp.net-core-2.0

10
推荐指数
4
解决办法
3万
查看次数

从ASP.NET Core依赖注入中获取ClaimsPrincipal或ClaimsIdentity

我有一个ClaimsIdentity像这样依赖的类:

public ClaimsIdentityDecorator(ClaimsIdentity identity)

这应该是当前用户的Claimsidentity.我通过IHttpContextAccessor类似的方式检索它:

services.AddScoped( x=>
{
    var context =  x.GetService<IHttpContextAccessor>();
    return context.HttpContext.User.Identity as ClaimsIdentity;
});
Run Code Online (Sandbox Code Playgroud)

我需要检查用户声明,并且似乎会自动为我注入ClaimsIdentity或ClaimsPrincipal或其他一些身份对象.从HttpContext中检索它并自己添加它很好.但是,如果有另一个对象或接口声明它已经存在,我想设计我的类来获取该依赖.

另外,我只想确保在Scope级别注入.

dependency-injection claims-based-identity asp.net-core

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

应用程序池的回收会杀死 Kestrel 但不会重新启动

背景

在 IIS 8+ 上托管(非核心)ASP.net 站点时,可以利用IIS 应用程序初始化模块在 IIS 启动时主动初始化(“预热”)Web 应用程序(或者,我相信,当应用程序池被回收时)。据我所知,在 IIS 上托管 .net Core 应用程序时这是不可能的。

我还注意到,在 IIS 上托管 .net Core (1.1) 应用程序时,dotnet.exe进程 (Kestrel) 作为应用程序池回收事件的一部分被终止。此过程仅在发出第一个新请求时才重新启动。

我问以下问题是因为我正在使用 Hangfire (Core) 和一个经常性的后台作业,并且希望在没有人长时间访问该站点时仍然执行该作业。

问题

  1. 在 IIS 上托管核心应用程序时,使用计划的应用程序池回收功能有什么意义吗?我能找到的唯一参考是 Github repo 上的一个问题

  2. 如果是这样,是否可以在应用程序池回收后自动初始化站点或启动 Kestrel(通常默认情况下每 29 小时发生一次)。

iis hangfire kestrel-http-server asp.net-core asp.net-core-2.0

8
推荐指数
0
解决办法
1668
查看次数

从 ASP.NET Core 应用程序启动外部进程 (.exe)

我有以下内容

[HttpPost]
public IActionResult LaunchExternalProcess()
{
    Process.Start("C:\\Windows\\System32\\calc.exe");
    return Ok();

}
Run Code Online (Sandbox Code Playgroud)

这在我的本地计算机上运行得很好,但是当部署到 IIS 10(Windows 2016)上时,我没有收到任何错误,但它不会在服务器上启动计算。

我只想通过页面上的按钮调用外部 .exe。

这是我正在使用的 javascript,它也适用于我的本地,但在服务器上没有错误,并且显示成功消息

$.ajax({
    url: "/Admin/LaunchExternalProcess",
    type: "POST",
    cache: false,

    success: function () {

        console.log("success");
    }
});
Run Code Online (Sandbox Code Playgroud)

iis asp.net-core-mvc kestrel-http-server asp.net-core asp.net-core-2.0

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

使用带有ASP.Net标识的Autofac将ApplicationUserManager传递给ApplicationOAuthProvider

我正在使用ASP.Net Identity并希望ApplicationUserManager通过以下文章将服务添加到我的所有自定义控制器:如何将我的Autofac容器插入ASP.NET Identity 2.1

这在我的控制器中完美运行,但是当我尝试通过在我的API上调用localhost:xxxx/token来创建令牌时.下面是调用的方法,但context.OwinContext.GetUserManager返回null.

我曾尝试注入ApplicationUserManagerApplicationOAuthProvider,但未能成功.你能指点我正确的方向吗?

编辑:10/15

好的,所以我已经进一步了,但我仍然卡住了.我能够使用以下内容初始化类:

    var x = new DatabaseContext();
    var store = new UserStore<ApplicationUser>(x);
    var options = new IdentityFactoryOptions<ApplicationUserManager>()
    {
        DataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ApplicationName")
    };

    builder.Register<DatabaseContext>(c => x);
    builder.Register<UserStore<ApplicationUser>>(c => store).AsImplementedInterfaces();
    builder.Register<IdentityFactoryOptions<ApplicationUserManager>>(c => options);
    builder.RegisterType<ApplicationUserManager>();

    builder.Register<ApplicationOAuthProvider>(c => new ApplicationOAuthProvider("self", new ApplicationUserManager(store, options))).As<IOAuthAuthorizationServerProvider>();
Run Code Online (Sandbox Code Playgroud)

这让我可以把它传递给ApplicationUserManagerApplicationOAuthProvider的构造函数.在Startup.Auth配置中,我使用以下内容初始化Provider:

OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = (IOAuthAuthorizationServerProvider)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IOAuthAuthorizationServerProvider)),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = …
Run Code Online (Sandbox Code Playgroud)

dependency-injection inversion-of-control autofac asp.net-web-api asp.net-identity-2

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

Mapper未初始化,我的单元测试Core.Net 2.0出错

我在Core.net 2.0中使用UOW和automapper完成了WebApi.一切都运行正常,但现在我想用Nunit实现单元测试,我有自动缓冲区的这个错误

消息:System.InvalidOperationException:Mapper未初始化.使用适当的配置调用Initialize.如果您正试图通过容器或以其它方式使用映射器实例,请确保您不必静态Mapper.Map方法的任何电话,如果你使用ProjectTo或UseAsDataSource扩展方法,确保你在适当的IConfigurationProvider通实例.

我该怎么解决这个问题.提前致谢 .Jolynice

AutoMapperProfile.cs类

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<Cars, CarsDTO>()
            .ReverseMap();
    }
}
Run Code Online (Sandbox Code Playgroud)

class Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public void ConfigureServices(IServiceCollection services)
    {

        //removed configurations 

        // Add cors
        services.AddCors();

        // Add framework services.
        services.AddMvc();

        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AutoMapperProfile>();
        });

        // Repositories
        services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
        services.AddScoped<IAccountManager, AccountManager>();
    }
}
Run Code Online (Sandbox Code Playgroud)

class carsController.cs

[Authorize]
[Route("api/[controller]")]
public class CarsController : Controller
{
private …
Run Code Online (Sandbox Code Playgroud)

c# testing automapper .net-core

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

在中间件中使用.NET Core会话

当我在.NET Core中编写可缩短链并返回响应的中间件时,它不会设置会话cookie。一个简短的例子:

public class Middleware
{

    private RequestDelegate _next;

    public Middleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var req = context.Request;
        if (req.Path.ToString() == "/hello-world")
        {
            context.Response.StatusCode = 200;
            context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
            await context.Response.WriteAsync("Hello, world!");
            return;
        }

        await _next(context);

    }

}
Run Code Online (Sandbox Code Playgroud)

这是我Startup班上的相关代码:

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddDistributedMemoryCache()
            .AddSession();
    }

    public void Configure(IApplicationBuilder app)
    {
        app
            .UseSession()
            .UseMiddleware<Middleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

传递响应头:

HTTP 200 No Error

Server: …
Run Code Online (Sandbox Code Playgroud)

session .net-core asp.net-core-middleware

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