gpt4 book ai didi

ssl - asp.net core 将 http 流量重定向到 https 问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:02:39 25 4
gpt4 key购买 nike

我刚刚在我的主机上安装了一个 ssl 证书,我想我会把所有的 http 流量重定向到 https。我发现在 .net 核心中有一个新的包可以帮助它。

问题是它对我不起作用,我不明白为什么。当我尝试导航到 http://mysite.co.uk 时测试重定向失败并显示一条消息

The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete. This problem can sometimes be caused by disabling or refusing to accept cookies.

这是我的 stratup.cs:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Playabout.Data;
using Playabout.Models;
using Playabout.Services;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using Microsoft.AspNetCore.Localization;
using Microsoft.Net.Http.Headers;
using System.Globalization;
using Sakura.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;
using System.Linq;
using Microsoft.AspNetCore.Rewrite;
using System.Net;

namespace Playabout
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
//builder.AddUserSecrets<Startup>();
}

builder.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>(
config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.Configure<GzipCompressionProviderOptions>
(options => options.Level = CompressionLevel.Optimal);
services.AddResponseCompression(options =>
{
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
{
"text/plain",
"text/css",
"application/javascript",
"text/html",
"application/xml",
"text/xml",
"application/json",
"text/json",
// Custom
"text/javascript",
"image/svg+xml"
});
options.Providers.Add<GzipCompressionProvider>();
});

services.AddMvc();


// Add application services.
services.Configure<SmtpConfig>(optionsSetup =>
{
//get from config.json file
optionsSetup.EmailDisplayName = Configuration["SMTP:DisplayName"];
optionsSetup.SmtpPassworrd = Configuration["SMTP:Password"];
optionsSetup.SmtpUserEmail = Configuration["SMTP:Email"];
optionsSetup.SmtpHost = Configuration["SMTP:Host"];
optionsSetup.SmtpPort = Convert.ToInt32(Configuration["SMTP:Port"]);
});
services.Configure<RecaptchaConfig>(optionsSetup =>
{
//get from config.json file
optionsSetup.RecaptchaPublicKey = Configuration["Recaptcha:PublicKey"];
optionsSetup.RecaptchaPrivateKey = Configuration["Recaptcha:PrivateKey"];
});
// Add default bootstrap-styled pager implementation
services.AddBootstrapPagerGenerator(options =>
{
// Use default pager options.
options.ConfigureDefault();
});
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddSession();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, IServiceProvider serviceProvider, ApplicationDbContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var supportedCultures = new[]
{
new CultureInfo("en-GB"),

};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-GB"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
app.UseRewriter(new RewriteOptions()
.AddRedirectToHttps());
app.UseResponseCompression();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
const int durationInSeconds = 60 * 60 * 730;
ctx.Context.Response.Headers[HeaderNames.CacheControl] =
"public,max-age=" + durationInSeconds;
}
});

app.UseSession();
app.UseIdentity();

// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});
app.UseGoogleAuthentication(new GoogleOptions()
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"]
});

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

try
{
await CreateRoles(context, serviceProvider);
}
catch (Exception)
{ }
}
private async Task CreateRoles(ApplicationDbContext context, IServiceProvider serviceProvider)
{
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
// Create a list of roles with both name and normalised name attributes
List<IdentityRole> roles = new List<IdentityRole>
{
new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" },
new IdentityRole { Name = "Member", NormalizedName = "MEMBER" },
new IdentityRole { Name = "Moderator", NormalizedName = "MODERATOR" }
};
// Check if the role already exists
foreach (var role in roles)
{
var roleExist = await RoleManager.RoleExistsAsync(role.Name);
if (!roleExist)
{ // Add it if it doesn't
context.Roles.Add(role);
context.SaveChanges();
}
}
var user = await userManager.FindByEmailAsync("markperry.uk@gmail.com");
if (user != null)
{
var gotRoles = userManager.GetRolesAsync(user);
if (!gotRoles.Equals("Admin"))
{
await userManager.AddToRoleAsync(user, "Admin");
}
}
else if (user == null)
{
var nuser = new ApplicationUser
{
FirstName = Configuration["AppSettings:Admin:FirstName"],
LastName = Configuration["AppSettings:Admin:LastName"],
PhoneNumber = Configuration["AppSettings:Admin:PhoneNumber"],
UserName = Configuration["AppSettings:Admin:UserName"],
Email = Configuration["AppSettings:Admin:Email"],
JoinDate = DateTime.Now,
EmailConfirmed = true,
PhoneNumberConfirmed = true
};
var result = await userManager.CreateAsync(nuser, Configuration["AppSettings:Admin:Password"]);
if (result.Succeeded)
{
await userManager.AddClaimAsync(nuser, new Claim("GivenName", nuser.FirstName));
await userManager.AddClaimAsync(nuser, new Claim("Surname", nuser.LastName));
await userManager.AddToRoleAsync(nuser, "Admin");
}
}
}
}
}

我添加到配置中的片段是:

        app.UseRewriter(new RewriteOptions()
.AddRedirectToHttps());

它使用 Microsoft.AspNetCore.Rewrite;

我刚刚使用 chrome 检查,它显示重复的重定向,并且由于“ERR_TOO_MANY_REDIRECTS”而失败,所以某些东西导致了循环。

有没有办法检查请求是否已经是“https”,或者有其他方法可以做事吗?

最佳答案

在花了一整天时间尝试解决这个问题、添加 [RequireHttps] 属性、尝试各种片段后,我在谷歌上搜索了这个问题,尝试传递 header ……最后我求助于我之前尝试过的东西' 似乎奏效了。我编辑了服务器上的 web.config 文件(我不知道如何在发布时执行此操作)添加以下内容:

  <system.webServer>
<rewrite>
<rules>
<rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAny">
<add input="{SERVER_PORT_SECURE}" pattern="^0$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>

摘自此处的评论:https://github.com/aspnet/KestrelHttpServer/issues/916

根据我的阅读,它与 Kestrel 有关,但我不完全确定是什么 :D 但它有效!每次发布都必须更改它会很烦人,所以明天我会尝试弄清楚每次如何为我完成这项工作。

关于ssl - asp.net core 将 http 流量重定向到 https 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42929062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com