How to ignore routes in MVC6 - asp.net-core

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();
}

Related

Displaying an HTML error page in ASP.NET Core

I would like to display an HTML error page when I catch a certain exception in my ASP.NET Core project. The page is stored in the project's root and I'm having trouble finding what I need to use in order to show this page. in this case, the application is already running and I would like the exception to be handled by redirecting the URL to the internally contained .html page.
What is the best practice for this?
If you want to execute custom error page,you could use UseStatusCodePagesWithReExecute and UseExceptionHandler middleware like below:
Controller:
public class ErrorController : Controller
{
[Route("Error/{statusCode}")]
public IActionResult StatusCodeError(int statusCode)
{
return Redirect("Index.html"); //Index.html located in wwwroot folder
}
}
Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseExceptionHandler("/Error/500");
app.UseHttpsRedirection();
app.UseStaticFiles();
//...
}
Error handling is built into ASP.NET Core. This docs page provides the overview.
The important bits are to configure the error handler within Configure method of Startup.cs:
app.UseExceptionHandler("/Error");
Then have a Razor page called Error.cshtml that handles and displays whatever content you'd like.

How to deploy ASP Core Web API VueJS site to IIS

I am new to VueJS and SPAs in general. I have created a new ASP Core site with a WebAPI controller for data and a VueJS front end. I am now trying to deploy this site to IIS and I am not sure how to do it correctly. I created a new application in IIS with an application pool set to "no-managed-code" and set the physical location to the VueJS app /dist folder. The site is loading, but I'm getting 404's for all of my service calls. I assume this is because the root of the site is set to the VueJS app folder instead of the root of the ASP Core folder. How do I set this up correctly to serve my app from myServer/mySite and also have my service endpoints as myServer/mySite/api/myController/myAction?
Scenario: Your dotnet core app has the API endpoints and you want to host the client site SPA on the same site. API calls will go through to the dotnet app and any other request will serve the index.html of the SPA.
.NET core supports this scenario with the methods from Microsoft.AspNetCore.SpaServices namespace like UseSpa()
Also note that in .NET 5 these extensions are moving to separate package Microsoft.AspNetCore.SpaServices.Extensions. It is available now but not well documented.
Your build SPA should go in ClientApp/dist in this example
e.g.
using Microsoft.AspNetCore.SpaServices;
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// In production, the SPA files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc();
// Must be near the end of the method because
// it will send any unhandled requests to index.html for SPA
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
// Development requests are send through to local node server
spa.UseProxyToSpaDevelopmentServer("http://localhost:8080/");
}
});
}
}

How to Redirect HTTP to HTTPs in 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();
...
}

Asp.Net Core middleware pathstring startswithsegments issue

Have a Asp.NET Core 2.0 application and I would like to map any path that does not start with /api to just reexecute to the root path. I added the below but doesn't seem to work:
app.MapWhen(
c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
a => a.UseStatusCodePagesWithReExecute("/")
);
Not using MapWhen() and just using app.UseStatusCodePagesWithReExecute("/") works for all paths not root. Just want to add filtering for all paths not root and not /api. Any ideas on how to do this?
Branched pipeline does not work correctly here because you have not added MVC middleware after status code page middleware. Here is the correct pipeline setup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.MapWhen(
c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
a =>
{
a.UseStatusCodePagesWithReExecute("/");
a.UseMvc();
});
app.UseMvc();
}
Note that middleware order matters here, you should add status code page middleware before MVC.
However using conditional pipeline seems like overkill here. You could achieve your goal with URL Rewriting Middleware:
var options = new RewriteOptions()
.AddRewrite(#"^(?!/api)", "/", skipRemainingRules: true);
app.UseRewriter(options);
app.UseMvc();

.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).