Kestrel on AspNet vNext doesnt serve index page under / - asp.net-mvc

I need to be able to serve my 'index.html', under the default url /, using Kestrel web server. Right now I'm only able to access my static files with the full path i.e /index.html
Again this works perfectly on VisualStudio, the context is OSX with Kestrel
This is my Startup.cs
public void ConfigureServices(DI.IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseMvc();
}
The solution I have so far, is to do a redirect inside a HomeController. But this is plain ugly, I'm trying to serve an static html file, which I honestly don't want it to be handled by my Application, if possible served directly from Kestrel.

You need to enable the DefaultFilesMiddleware using UseDefaultFiles() and place it before the call to UseStaticFiles():
app.UseDefaultFiles();
app.UseStaticFiles();
If you don't specify otherwise, the middleware uses the DefaultFilesOptions by default, which means this list of default file names will be used:
default.htm
default.html
index.htm
index.html
See MSDN

Related

.net attribute routes not matched in production

I have a asp.net v6 mvc project with an spa front end that works fine in development. (Following the new pattern where my spa dev server has a proxy configuration to forward api requests to the .net app).
When I deploy this to IIS, my api routes (all beginning "api/") are no longer recognised, and all api requests are redirected to the fallback spa home page. What's going on ?
This is my Configure method, in Startup.cs
public void Configure(IApplicationBuilder builder, IWebHostEnvironment env)
{
...
builder.UseStaticFiles();
builder.UseRouting();
builder.UseEndpoints(endpoints =>
{
// I added this line to try and fix my problem. It's not necessary in dev, but still broken in prod.
endpoints.MapControllers();
// This was all I had in dev, but all my Controller actions have AspNetCore.Mvc Route attributes.
endpoints.MapControllerRoute(
name: "default",
pattern: "api/{controller}/{action=Index}/{id?}");
// I know this method is called and used, because if I change "index.html" everything breaks and I'm no longer redirected to my spa
endpoints.MapFallbackToFile("index.html");
});
}
Here is a controller...
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class AllItemsController : ControllerBase
{
[Route("api/all-items")]
public ApiResponse<List<Item>, string> Get()
{

How the serve static html files with vaadin router

I have te following route configuration in my hilla app
router.setRoutes([
{path: '/', component: 'home-view'},
]);
this is works, but I need to publish some static html files. Not sure where to put the files and how to configure router to make them accessible with URL like /myfile.html?
already tried to put them in /frontend folder and add route, but does not work but creates a loop
{
path: '(.*)\.html',
action: (ctx, commands) => {
window.location.pathname = ctx.pathname;
}
}
Found it here How do I deliver static html pages with vaadin router (client side)?
The server is a Spring Boot server so any file you put inside src/main/resources/META-INF/resources is made available, e.g. if you create src/main/resources/META-INF/resources/myfile.html then you can access it as http://localhost:8080/myfile.html.
If you are just loading a static HTML page there is no need to configure the router for it. For a link you can add router-ignore so that router will not try to intercept it, e.g. `"

How do you change the Swagger favicon?

I am building a ASP.NET CORE Web API and using Swagger for the documentation. I have not been able to change the favicon. I have a swagger-ui directory under wwwroot where I have placed my favicon but the favicon is never there. Also, I am changing the favicon using favascript in a custom js file.
So, how does one change the favicon for Swagger?
You need to inject jscript as below:
1- Create /assets/js/docs.js as below:
(function() {
var link = document.querySelector("link[rel*='icon']") || document.createElement('link');;
document.head.removeChild(link);
link = document.querySelector("link[rel*='icon']") || document.createElement('link');
document.head.removeChild(link);
link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = '../assets/images/logo_icon.png';
document.getElementsByTagName('head')[0].appendChild(link);
})();
2- Load the script in your startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
{
app.UseSwaggerUI(
options =>
{
options.InjectJavascript("../assets/js/docs.js");
});
}
Note: Make sure you enable static files in your .NET Core Configure method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
{
app.UseStaticFiles(); // For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "assets/images")),
RequestPath = "/assets/images"
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "assets/js")),
RequestPath = "/assets/js"
});
}
This is what worked for me:
First, you have to create the wwwroot folder, and place there a folder called swagger. Edit your csproj to include this line:
<ItemGroup>
<None Include="wwwroot\*" />
</ItemGroup>
Files under this directory must be Content, Do not copy. That's default option anyway.
Then, you have to place two png files called favicon-16x16.png and favicon-32x32.png in swagger folder.
Last thig to do, add app.UseStaticFiles(); before app.UseSwaggerUI(); to get it to work.
You can also add a favicon.ico under wwwroot folder.
** NOTE: In case you had modified endpoint url, using app.UseSwaggerUI(config => config.SwaggerEndpoint("my/swagger/doc/file.json", "Rest API"));, directory tree under wwwroot must match the url. i.e., wwwroot/my/swagger/doc/favicon-16x16.png and wwwroot/my/swagger/doc/favicon-32x32.png.
This can also be achieved if you simply place your favicon.ico at the root within wwwroot folder: wwwroot/favicon.ico. Being placed at the root, the favicon.ico be used as the default browser tab icon.
Of course as previously stated, you need to make sure you have app.UseStaticFiles(); in your Configure() method in order to serve the files within wwwroot.
Lastly also make sure you have the following in your .csproj file:
<ItemGroup>
<None Include="wwwroot\*" />
</ItemGroup>
You have to essentially override it. By default, Swagger UI sets the icon to pull from your Swagger UI root. For example, if you load the docs at /swagger-ui, then the favicon is being pulled from /swagger-ui/favicon-32x32.png and /swagger-ui/favicon-16x16.png. Therefore, you can add this directory to your wwwroot and add your own favicon images there.

Dropwizard 0.8.0: serve static assets from /

I want my server to serve the static html files from /. Furthermore, css and js files should be served from /css respectively, /js. All json data should be accessible at /api.
However, I get a 404 for http://localhost:8080/ or any other path.
I use the following setting in the configuration file:
server:
type: simple
rootPath: /api/*
The application.initialize method looks like this:
#Override
public void initialize(io.dropwizard.setup.Bootstrap<MyConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/assets/css", "/css", null, "css"));
bootstrap.addBundle(new AssetsBundle("/assets/js", "/js", null, "js"));
bootstrap.addBundle(new AssetsBundle("/assets/pages", "/", "index.html", "html"));
}
I've just had to work through a similar problem (The documentation isn't the clearest, although with hindsight I guess most of the information is there somewhere), which I've resolved by setting both the applicationContextPath and the rootPath in my application config:
server:
type: simple
rootPath: /api/*
applicationContextPath: /
The default value for applicationContextPath is "/application" in a simple server, so your complete root-path would have been "/application/api/*". If you don't need to use the simple server, you could alternatively use the default server, which has the applicationContextPath set to "/" by default:
server:
rootPath: /api/*

Project subdirectory as root for static files

New to ASP.NET MVC, I am creating a web application using the Visual Studio 2013 wizard. It creates several folders from where static files are served: Content, Scripts, etc.
Frameworks in other languages (e.g. TurboGears) have an explicit directory only for static content, removing the risk of serving the source code of a page instead of processing it which is a typical configuration mistake of PHP sites.
ASP.NET however is happy to deliver anything in the application's root directory, e.g. http://localhost:1740/Project_Readme.html as long as it has the right extension. Only the Views folder is protected with a Web.config.
How do I configure the application to use another directory than the project's root directory for static files. E.g. if the file favicon.ico is put into the subdirectory Content, it should be accessible as http://localhost:1740/favicon.ico, but nothing outside of the Content directory unless returned by a controller.
Nothing should ever be executed in this directory, that is, if *.cshtml files are put into this directory, the files' contents (the source code) should be delivered as text/plain.
Final application will run using mod_mono on Linux.
Update:
Ben,
The proposed solution works only with Owin. To get it working in an MVC application you have to use asp.net MVC 6 (part of asp.net core or asp.net 5) only. But, with Web API you can use the older versions too. To setup the application please use the following steps:
Create an empty project using visual studio templates(don't select Web API or MVC)
Add the following Nuget packages to the project:
Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.StaticFiles
Add a Startup.cs file and decorate the namespace with the following
[assembly: OwinStartup(typeof(Startup))]
Add the following code to the Stratup.cs class
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);
//Configure the file/ static file serving middleware
var physicalFileSystem = new PhysicalFileSystem(#".\client");
var fileServerOptions = new FileServerOptions
{
EnableDefaultFiles = true,
RequestPath = PathString.Empty,
FileSystem = physicalFileSystem
};
fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"};
fileServerOptions.StaticFileOptions.ServeUnknownFileTypes = true;
fileServerOptions.StaticFileOptions.FileSystem = physicalFileSystem;
app.UseFileServer(fileServerOptions);
app.UseWebApi(config);
}
This should do the magic. Now you can host the application in IIS. IIS will serve the static assets only from client folder. Add Server folder and add controllers.
The Microsoft.Owin.Host.SystemWeb is what facilitates the hosting of Owin application in IIS. The file serve options help IIS to serve static files only from client folder.
Please let me know if you have any questions.
Based on your question, the project structure that you want to achieve should be like the following.
Basically you will have two folders only, Client and Server. Static files are served from client folder only. Server folder is not accessible. If this is what you need then it can be achieved easily with Owin Self Host with Static File Serving middleware.
Self host works with out any dependency on IIS. But, if your planning to host this application on Linux, you could use Asp.NET CORE 1.0. Later if you decide to host the application on IIS inside windows that can be achieved easily by adding the Microsot.Owin.Host.SystemWeb nuget package.
There are great blog posts on this topic. This is the link for one of them. Here is the link for achieving the same in Asp.NET Core.
I hope this solves your issues and please let me know if you have any questions.
Thank you,
Soma.
The best solution I found is to ignore asp.net normal way and write a new way
public override void Init()
{
BeginRequest -= OnBeginRequest;
BeginRequest += OnBeginRequest;
}
protected void OnBeginRequest(object sender, EventArgs e)
{
if (Request.Url.AbsolutePath.StartsWith("/endPoint"))
{
Context.RemapHandler(endPoint);
}
else
{
Context.RemapHandler(staticHandler);
}
}
Let endPoint and staticHandler implement IHttpHandler
it works but every static file moves through c# so there might be a solution with better performance

Resources