Tag: asp.net core 2.0

Cookie身份validation提前到期

问题 在我的ASP.NET MVC Core 2.0应用程序中,我设置了使用cookie身份validation方案而不使用Identity,因为我们拥有自己的后端身份validation存储和api。 身份validation和授权每次都能完美运行。 但是,无论登录/会话在大约30分钟后过期。 您可以看到我们将身份validationcookie和会话cookie的超时设置为120分钟。 应用信息: 平台:.Net 4.7.x(Windows) 框架:Asp.Net Core 2.x IIS用作代理服务器 如何解决这个问题的任何帮助或意见都将受到欢迎 码 更新:用services.AddDistributedRedisCache(..)替换services.AddMemoryCache() – 测试看看它是如何工作的 Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddDistributedRedisCache(options => { options.Configuration = “localhost”; options.InstanceName = “CoreTestInstance”; }); services.AddAuthentication(“CookieAuthenticationScheme”) .AddCookie(“CookieAuthenticationScheme”, options => { options.Cookie.Name = authSettings.Name; options.Cookie.HttpOnly = false; options.Cookie.Expiration = TimeSpan.FromMinutes(120); options.ExpireTimeSpan = TimeSpan.FromMinutes(120); options.AccessDeniedPath = […]

将文本添加到URL而不是int ID

目前我们的固定链接不正确并阻碍搜索,例如https://example.com/en/blogs/19 – 这应该包含Google可以在搜索中找到的URL,而不是使用的int id从Db中检索。 假设我们能够编辑包含关键字的链接,那么我们可以说一篇关于“汽车行业最新动态”的文章会给算法带来更大的影响。 例如: https://example.com/en/blogs/news/The_Automotive_Industry_Latest : https://example.com/en/blogs/news/The_Automotive_Industry_Latest – 此链接应指向https://example.com/en/blogs/19 我可以通过使用以下内容来实现这一点 – 但这是实现这一目标的方法吗? [Route(“en/blogs”)] public class BlogController : Controller { [HttpGet(“{id}”)] [AllowAnonymous] public IActionResult GetId([FromRoute] int id) { var blog = _context.Blogs.Where(b => b.Id == id); return Json(blog); } [HttpGet(“{text}”)] [AllowAnonymous] public IActionResult GetText([FromRoute] string text) { var blog = _context.Blogs.Where(b => b.Title.Contains(text)); if(blog […]

是否真的需要.net core 2 API中的services.AddSingleton

我在.NET Core 2 Web API Controller中访问了appsettings.json,只需添加以下内容: public class MyController : Controller { private readonly IConfiguration appConfig; public MyController(IConfiguration configuration) { appConfig = configuration; } } 在services.AddMvc();之后没有在Startup类ConfigureServices(IServiceCollection服务)中添加以下内容: services.AddSingleton(Configuration); 我的方法有什么缺陷吗? 在.Net Core 2配置部分的官方文档中,没有提及使用’AddSingleton’甚至一次: https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration 也通过搜索我无法找到访问配置的相关内容! https://docs.microsoft.com/en-us/search/index?search=AddSingleton&scope=ASP.NET+Core 下面的链接显示AddSingleton,如同必须的步骤 : 访问控制器类中的appsettings.json值 https://blogs.technet.microsoft.com/dariuszporowski/tip-of-the-week-how-to-access-configuration-from-controller-in-asp-net-core-2-0/

如何unit testingHttpContext.SignInAsync()?

SignInAsync()源代码 我遇到了unit testing的一些问题。 DefaultHttpContext.RequestServices为null 我试图创建AuthenticationService对象,但我不知道要传递什么参数 我该怎么办? 如何unit testingHttpContext.SignInAsync() ? 测试方法 public async Task Login(LoginViewModel vm, [FromQuery]string returnUrl) { if (ModelState.IsValid) { var user = await context.Users.FirstOrDefaultAsync(u => u.UserName == vm.UserName && u.Password == vm.Password); if (user != null) { var claims = new List { new Claim(ClaimTypes.Name, user.UserName) }; var identity = new ClaimsIdentity(claims, “HappyDog”); […]

启动时没有加载Automapper配置文件?

我正在使用: AutoMapper 6.1.1 AutoMapper.Extensions.Microsoft.DependencyInjection 3.0.1 似乎我的配置文件没有被加载,每次我调用mapper.map我得到AutoMapper.AutoMapperMappingException:’缺少类型映射配置或不支持的映射。 这是我的Startup.cs类的ConfigureServices方法 // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //register automapper services.AddAutoMapper(); . . } 在另一个名为xxxMappings的项目中,我有我的映射配置文件。 示例类 public class StatusMappingProfile : Profile { public StatusMappingProfile() { CreateMap() .ForMember(t => t.Id, s => s.MapFrom(d => […]

为什么Scoped服务解析为同一请求的两个不同实例?

我有一个包含List的简单服务。 在Startup.cs中,我使用的是services.addScoped()方法。 我在两个不同的地方(控制器和中间件)注入服务实例,对于单个请求,我希望获得相同的实例。 但是,这似乎并没有发生。 即使我在Controller Action中向List添加Foo,中间件中的Foo列表也始终为空。 为什么是这样? 我已经尝试使用AddSingleton()将服务注册更改为单例,并且它按预期工作。 但是,这必须限制在当前请求范围内。 非常感谢任何帮助或想法! FooService.cs public class FooService { public List Foos = new List(); } Startup.cs … public void ConfigureServices(IServiceCollection services) { … services.AddScoped(); } [以下是我注入服务的两个地方,导致两个不同的实例] MyController.cs public class MyController : Controller { public MyController(FooService fooService) { this.fooService = fooService; } [HttpPost] public void TestAddFoo() { //add foo […]

ASP.NET Core 2.0 MVC自定义数据库初始化程序类上的ObjectDisposedException

我在自定义数据库初始化程序类中遇到以下exception: 发生System.ObjectDisposedException HResult = 0x80131622 Message =无法访问已处置的对象。 此错误的常见原因是处理从依赖项注入解析的上下文,然后尝试在应用程序的其他位置使用相同的上下文实例。 如果您在上下文中调用Dispose()或将上下文包装在using语句中,则可能会发生这种情况。 如果使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例。 Source = StackTrace:Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()at Microsoft.EntityFrameworkCore.DbContext.d__48.MoveNext()at System.Runtime .ExceptionServices.ExceptionDispatchInfo.Throw() 位于System.Runtime.Exception服务9.d__22.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 9.d__22.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 9.d__22.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 1.GetResult()at Microsoft.AspNetCore.Identity.UserManager 1.d__73.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 1.d__73.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() […]

如何使用存储在.NET Core 2中的Azure Key Vault中的PFX证书中的私钥?

我在C#中编写了一个ASP.NET Core 2.0网站并启用了Facebook身份validation,因此它需要HTTPS。 我正在使用原生的Kestrel Web服务器来托管该站点,并且有一个监听器设置为每个MS文档获取PFX证书。 从Key Key召回后,我似乎找不到让Kestrel识别私钥的方法。 我知道它存在,因为我写了两个调试语句,表明它实际存在。 这是我用来检索秘密的function,它正在工作。 public static async Task GetKeyVaultCert() { X509Certificate2 pfx; try { var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken)); var secret = await kvClient .GetSecretAsync(“https://macscampvault.vault.azure.net/secrets/letsencrypt”).ConfigureAwait(false); byte[] bytes; if(secret.ContentType == “application/x-pkcs12”) bytes = Convert.FromBase64String(secret.Value); else { bytes = new byte[0]; Console.WriteLine(“secret is not PFX!!”); throw new ArgumentException(“This is not a […]

如何让JWT在Autorest生成的SDK中工作? (ASP.NET Core 2.0)

我希望能够使用用户名和密码登录我的身份数据库并检索JWT。 然后我想使用JWT从我的API安全地访问数据。 我发现VS2017生成的SDK代码使用了旧版本的autorest,因此我已切换到使用Azure Autorest api和SDK都是ASP.NET Core 2.0 要生成我使用的SDK AutoRest -mynamespace mytrack.Client -CodeGenerator CSharp -Modeler Swagger -Input swagger.json -PackageName mytrack.client -AddCredentials true 版本显示为 AutoRest code generation utility [version: 2.0.4262; node: v8.11.2] 我把我的考试写成了 using System; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using swagger; // my name space from the autorest command, not to be confused […]

升级到Core 2 Preview 2后获取“无法解析类型的服务..”

我刚刚升级到ASP.NET Core 2 Preview 2并遇到了dependency injection的问题。 我明白了 在运行项目时,无法为类型为“LC.Tools.API.Startup”的方法“Configure”的参数“context”解析类型为“LC.Tools.API.Data.GenericDbContext”的服务。 使用旧版本时我没有遇到此问题。 DbContext(GenericDbContext): namespace LC.Tools.API.Data { public class GenericDbContext : DbContext { public GenericDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { //Generic builder.Entity(); builder.Entity(); . . . . . //Shop builder.Entity().ToTable(“ShopClient”); builder.Entity().ToTable(“ShopCategory”); . . . . . . } } Startup.cs: namespace LC.Tools.API { […]