How to Redirect HTTP to HTTPs in ASP.NET Core? - asp.net-core

I want to redirect a HTTP request to HTTPS. How can I do in .Net Core 2.0?
I tried to add the below code in the startup.cs file but this is not working. Can any one help me for this?
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 443;
});
Details about the code:
When I run my project first time, the Configure() and AddHttpsRedirection() gets called.
Then after I change https to http only after that it's not working means its not call any function from stratup.cs
I did this code and try to redirect to https, but page is just loading, it's not redirecting, Even worse, I am not able to call AddHttpsRedirection function.

I have a .NET Core 2.1 project and I use the following:
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services)
{
...
app.UseHttpsRedirection();
...
}

Related

Swashbuckle Swagger Try It Out behind NGINX reverse proxy

I'm trying to make the swaggerUI Try it out function to work behind NGINX reverse proxy.
I'm using ASP.net Core with the package Swashbuckle Swagger
Since I have multiple API I added a subdomain to my nginx config.
When I use try it out it sends the request to
http://{server-ip-address}/api/myendpoint
instead of
http://{server-ip-address}/myapi/api/myendpoint
My goal is to add the myapi to the address of Try it out function.
I'm not sure if I should edit my NGINX config or my ASP.net core configuration.
Thanks for your help!
You can try in Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseSwagger(opt =>
{
opt.PreSerializeFilters.Add((swagger, httpReq) =>
{
var serverUrl = $"http://{httpReq.Host}/myapi/api/myendpoint";
swagger.Servers = new List<OpenApiServer>{new() { Url = serverUrl }};
});
});

In .Net Core 5, How to redirect www to non-www URL?

On a subdomain want to redirect all requests with www to non-www, because of that, using this line of code in the "Start.up", in the "Configure" method like below but it doesn't work.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseRewriter(new RewriteOptions().AddRedirectToNonWww());
...
}
...
}
What's wrong with my codes? I don't want to write some extra codes like this, because it seems there is a function to handle it.
in .net Core 5 put the follow code inside Strartup.cs Configure function
app.UseRewriter(new RewriteOptions()
.AddRedirectToNonWwwPermanent()
.AddRedirectToHttps()
);
If you use .net Core 6 put the code inside program.cs

ASP.Net Core SignalR simple host - 404 error

I am wanting to have 1 simple console app host that is solely for self-hosting the SignalR component.
I have created an "Empty Web Application" using the template. I have created a very simple StartUp file that does not contain anything like MVC etc as it is not needed. However I am getting a 404 not found error from the browser when attempting to negotiate.
The Startup file is as follows:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseSignalR(routes =>
{
routes.MapHub<Masterhub>("masterhub");
});
}
}
As you can see, it is very basic, but as I don't want any MVC/Web API functionality, I didn't include all of that setup. There is setup for CORS and SignalR, that is all.
Is what I am attempting to do possible?
It turns out that the JavaScript file I was using from the web client to connect to the self-hosted SignalR Console Application, was the old full .Net version, and not the new version you can get from NPM.

.NET Core rc2 WebAPI with index.html as default page

I have set up an empty WebAPI project with .NET Core rc2 and have it wired up with Angular2 rc1. Angular will handle everything view related and the WebAPI is the backend.
When I start the app by default it comes up with localhost:4578/api/values from the default API controller as startpage.
However, I want it to show index.html by default which is located in wwwroot and is hosting my Angular2 app.
In Startup.cs the Configure method looks like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
app.Run(ctx =>
{
ctx.Response.Redirect("/index.html");
return Task.FromResult(0);
});
}
app.UseStaticFiles and the app.Run lambda need to be in place for the manual redirect to index.html to work but it still comes up with /api/values as default start page.
I know that for debugging purposes I can change the start page easily but I want to change it such that when I host it it always serves index.html as start page.
How can I change this?
When creating a new empty WebAPI project, the launchsettings.json file points to api/values by default. To change it, go to the launchsettings.json file in your project:
and change the launchUrl value to: http://localhost:4578 (from http://localhost:4578/api/values).

How to ignore routes in MVC6

I'm developing a very simple SPA style application and I don't want to use razor, so I just need it to serve up HTML files (from the wwwroot folder), except for when the js calls my API controllers. In Web API 2 you could get the router to ignore HTML files so they are served directly e.g.
config.Routes.IgnoreRoute("Html", "{whatever}.html/{*pathInfo}");
similar to this example: http://www.strathweb.com/2014/04/ignoring-routes-asp-net-web-api/ is the IgnoreRoute functionality just not implemented or has it been changed?
At the moment if I have app.UseMvc(); in my Startup.cs any get request to "/" gets me this exception:
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml.
Microsoft.AspNet.Mvc.Rendering.ViewEngineResult.EnsureSuccessful()
But when I leave it without MVC it serves up the index.html file when you request "/" - obviously my API controllers won't work then though.
I think if you want to serve index.html even when your MVC option is enabled? If so you have to change one setting.
When you enable MVC there is a default route added to search for Home/Index when your url is like http://localhost:yourport.
When you disable MVC it will serve index.html as no route is present in that case.
So if you want to serve index.html when MVC is enabled then add the following in Configure function before using MVC.
app.UseDefaultFiles(new Microsoft.AspNet.StaticFiles.DefaultFilesOptions() { DefaultFileNames = new[] { "index.html" } });
// your UseMVC goes here.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}