问题
I've published a brand new out-of-the-box app in Azure App Service using a F1 (free) App Service Plan.
I have the following class to redirect incoming request like www.mywebapp.azurewebsites.net/ to https://mywebapp.azurewebsites.net/ :
public class NonWwwRule : IRule
{
public void ApplyRule(RewriteContext context)
{
var req = context.HttpContext.Request;
var currentHost = req.Host;
if (currentHost.Host.StartsWith("www."))
{
var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 80);
var newUrl = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
context.HttpContext.Response.Redirect(newUrl.ToString(), true);
context.Result = RuleResult.EndResponse;
}
}
}
My Startup.cs is like that:
public class Startup
{
private readonly IWebHostEnvironment _env;
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
_env = env;
var builder = new ConfigurationBuilder().AddEnvironmentVariables();
Configuration = configuration;
builder.AddUserSecrets<Startup>();
}
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.AddControllersWithViews();
services.AddSingleton<IConfiguration>(Configuration);
services.AddMvc();
if (_env.IsDevelopment())
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 5001;
});
}
else
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
}
// 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();
}
var options = new RewriteOptions();
options.AddRedirectToHttpsPermanent();
options.Rules.Add(new NonWwwRule());
app.UseRewriter(options);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Now if I request http://mywebapp.azurewebsites.net/ I'm redirected to https://mywebapp.azurewebsites.net/ and this is correct.
If I simply request mywebapp.azurewebsites.net/ I'm redirected to https://mywebapp.azurewebsites.net/ as well, and this is also correct.
Now, if I request www.mywebapp.azurewebsites.net/ I get an error message telling me "We can’t connect to the server at www.mywebapp.azurewebsites.net"
Adding a new if statement in the NonWwwRule class like this:
if (currentHost.Host.StartsWith("localhost"))
{
var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 80);
var newUrl = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
context.HttpContext.Response.Redirect(newUrl.ToString(), true);
context.Result = RuleResult.EndResponse;
}
and starting the app with F5 (with debugger) shows me that the class works well and I'm redirected to https://lhost:44347/ instead of https://localhost:44347/. The first 4 letters are cut-off.
What I'm doing wrong?
EDIT:
I've also tried the following code instead of the NonWwwRule class (commented out in the Startup.cs class):
app.UseRewriter(new RewriteOptions()
.AddRedirect("^home/index$", "home/privacy")
.AddRedirect("^www.(.*)", "https://$1")
.AddRedirect("^www.(.*)", "$1")
.AddRedirect("(.*)/$", "$1")
.AddRedirectToHttpsPermanent());
The only rule that works is if I ask for https://mywebbapp.azurewebsites.net/home/index, then I'm redirected to https://mywebbapp.azurewebsites.net/home/privacy
After having verified that the Redirect middleware workd, I've commented out redirecting home/index and IÄve tried the other ones, one by one, having firts verified the syintax them with https://regex101.com/
I've also tried another way instead of the redirect middleware, editing simply the web.config file in the Azure portal, according to the rule below (Please, refer to the section "Redirect www to non-www" on this page) https://blog.elmah.io/web-config-redirects-with-rewrite-rules-https-www-and-more/
My conclusion is that somehow Azure with App Service plan in a free tier is preventing/blocking redirecting to whatever may look as a custom domain. Is that correct? Any other successful experience redirecting within aa Azure free tier?
Thanks a lot
Regards
来源:https://stackoverflow.com/questions/62581721/redirecting-asp-net-core-3-1-mvc-web-app-not-working