Static directory with ktor - not under "mysite.com/static/..." - ktor

I read through Serving Static Content and am having a brain-block.
I've got a folder /resources/static. It has static stuff in it. Some of that stuff is index.html, favicon.ico, a css folder, a js folder, etc.
I want it to show up as https://example.org/favicon.ico, https://example.org/ (default to index.html), etc.
All the examples in the Docs are for a site that shows up as https://example.org/static/index.html
I'm not getting the difference between "static", "resource", "resources", "files"
routing {
static("static") {
files("css")
files("js")
file("image.png")
file("random.txt", "image.png")
default("index.html")
}
}

static("static") - this is saying that when a client requests [your_host]/static then use the static handler to deal with the request.
Each of the configured handlers will run in order until the first one matches, so if no files match the request under the css directory then the next will run.
files("css") - this tells the static handler to look in a folder called css locally to serve the static content (i.e. client asks for [your_host]/static/style.css will get [app_directory]/css/style.css
file("image.png") - this tells the static handler to return the local file to serve the static content (i.e. client asks for [your_host]/static/* will get [app_directory]/image.png
default("index.html") - this will serve the local file [app_directory]/index.html for any request [your_host]/static/*
resource, resources and defaultResource do the same thing but for resources built in to your app, rather than on the file system.

This MAY have done it.
static("/") {
resources(resourcePackage = "static")
}
defaultResource(resource = "index.html", resourcePackage = "static")

Related

Check if request is made to Razor Page

How can I check within middleware code if current request is made to Razor Page not to any other resource (static file, or API)?
All my APIs are located within api folder, so if (!context.Request.Path.StartsWithSegments("/api")) {} filters out APIs, but that will not work for static content as these files and libraries are placed within number of folders what results in number of URL segments.
Could not find any relevant property in context.
First step - place the middleware after app.UseRouting(). Any request for a static file will never reach your middleware because the static files middleware will short circuit the request. Also, after this point, the routing middleware will have selected the endpoint and populated the endpoint metadata. Then you can test the endpoint metadata collection to see if it includes PageRouteMetaData, which tells you that this is a Razor page route:
app.Use((context, next) => {
var endpoint = context.GetEndpoint();
if (endpoint != null)
{
foreach(var md in endpoint.Metadata)
{
if( md is PageRouteMetadata)
{
// this is a page route
}
}
}
return next(context);
});

What is the difference between static files and embedded application resources in Ktor?

I'm reading the ktor documentation on serving static content and it's not clear to me what the difference between files("css") and resources("css") is.
The static method is equivalent to the route method so it just creates a path route in the routing tree.
The files method allows serving all static files from the provided path (directory) from a local filesystem. Relative paths will be resolved using the current working directory.
The resources method does the same as the files method except that it allows serving static files from the classpath.
Here is an example:
// Assume that current working directory is /home/user/project
embeddedServer(Netty, port = 8080) {
routing {
// This route will be resolved if a request path starts with /assets/
static("assets") {
// For the request path /assets/style.css the file /home/user/project/css/style.css will be served
files("./css")
// It's the same as above
files("css")
// For the request path /assets/data.txt the file /absolute/path/to/data.txt will be served
files("/absolute/path/to")
// For the request path /assets/style.css the file <resources>/css/style.css will be served
// where <resources> is the embedded resource directory
resources("css")
}
}
}.start(wait = true)

.NET Core serving HTML file outside wwwroot can't load JS files

I am experimenting with different ways to secure an Angular CLI app with .NET Core Authorization.
To make it as secure as possible, I would like to keep all of the Angular CLI output files from being publicly available and keep them in the default "dist" folder preconfigured by the CLI.
I can load the index.html from an authorized controller by returning a PhysicalFileResult...
public IActionResult Index()
{
return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "dist", "index.html"),"text/HTML");
}
But I get 404s on all of the bundle.js files when the page loads.
Is it possible to serve the app this way without involving the static file middleware or making the files publicly available (preferably without having to manually change the src for each bundled js file in index.html)?
Take a look at this article from the asp.net core docs (excerpt included below): https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files#static-file-authorization
Just place your authorization middleware before the static one.
// has to be first so user gets authenticated before the static middleware is called
app.UseIdentity();
app.Use(async (context, next) =>
{
// for pathes which begin with "app" check if user is logged in
if(context.Request.Path.StartsWith("app") && httpContext.User==null)
{
// return "Unauthorized"
context.Response.StatusCode = 401;
return;
}
// If user is logged in, call next middleware
await next.Invoke();
});
app.UseStaticFiles();

Use of AuthConfig, BundleConfig, FilterConfig , RouteConfig and WebApiConfig in App_Start() folder in MVC

Can you please explain in detail, the use of App_Start() folder in MVC4?
I see that this folder is actually not available in previous versions of MVC.
There are 5 files in this folder.
AuthConfig
BundleConfig,
FilterConfig,
RouteConfig,
WebApiConfig.
App_Start is just another folder that groups together ASP.NET MVC configuration, which in previous versions of ASP.NET MVC was done in Global.asax.
ASP.NET MVC introduces more and more configuration elements, and this folder is ideal to place this configuration. For example, MVC 5's new auth. configuration, such as for third-party login providers, are also placed within this folder (in Startup.Auth.cs).
App_Start is not a ASP.NET special folder recognized by ASP.NET/IIS. You can rename the folder if you want. The name is just a convention, like App_GlobalResouces etc.
Update:
Below are some information and reference points for each file. The use of these files are pretty straightforward. I have included few online references that might help your to understand more.
AuthConfig — registers external authentication providers.
See ASP.NET MVC external authentication providers for more information.
BundleConfig — registers your CSS and JS so they can be bundled and minified. See also ASP.NET MVC: Guidance: Bundling and Minification.
WebApiConfig — only applicable if you are using Web API. It can be used to configure Web API-specific routes, any Web API settings and Web API services. See also configuring ASP.NET MVC Web API 2
FilterConfig — registered global filters. These filters are applied to all actions and controllers. See also ASP.NET MVC 3: Global action filters
RouteConfig — you already found information.
App_start folder has been introduced in Mvc4. It contains various configurations files like:
BundleConnfig.cs
FilterConfig.cs
RouteConfig.cs
WebApiConfig.cs
AuthConfig.cs
App_start is not a special folder in MVC nor the class files inside this, these are just normal class files with different application
configurations(filtering, bundling, routing etc.) and all these settings gets registered within Application_Start method of Global.asax.cs file.
BundleConfig.cs:
This is used to create and register bundles for CSS and JS files. for
eg. jQuery,jQueryUI,jQuery validation,Modernizr and Site CSS..
Bundling and minification are two techniques to improve request load time by
reducing the number of requests to the server and reducing the size of
requested assets (such as CSS and JavaScript.)
Microsoft provides assembly Microsoft.Web.Optimization for the same
for eg.
Lets create two Bundles. one for style(css) and another for script(javascript)
You can create bundle for css and javascripts respectively by calling
BundleCollection class Add() method within BundleConfig.cs file.
STEP 1:
Creating Style Bundle
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
Creating Script Bundle
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js"));
STEP 2:
Above bundles are defined in BundleConfig class as:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
//Adding StyleBundle to BundleCollection
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
//Adding ScriptBundle to BundleCollection
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js"));
}
}
STEP 3:
Registering Bundle
All bundles are registered in the Application_Start event of Global.asax:
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Minification is a technique for removing unnecessary characters (like
white space, newline, tab) and comments from the JavaScript and CSS
files to reduce the size, in turn improve load time of a web page. for
eg. jquery-1.7.1.min.js is the minified js file for jquery-1.7.1,
mostly used for production environment, for non-prod you can better use non-
minified js to have better readability.
for eg.
A Jquery function in uncompressed js may look something like:
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
same above function in compressed or minified js will look like:
!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}
FilterConfig.cs:
This is used to create and register global MVC filter:
for eg.
Authentication filters (Executed First)
Authorization filters
Action filters
Result filters
Exception filters (Executed Last)
Note: As mentioned above Filters are executed in an order.
for eg. Authentication Filters introduced with MVC5:
public interface IAuthenticationFilter
{
void OnAuthentication(AuthenticationContext filterContext);
void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}
You can create your CustomAuthentication filter attribute by implementing
IAuthenticationFilter as shown below-
public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
//logic goes here
}
Runs after the OnAuthentication method
public void OnAuthenticationChallenge(AuthenticationChallengeContext
filterContext)
{
{
//logic goes here
}
}
Configuring Filters
You can configure your own custom filter into your application at
following three levels:
Global level
By registering your filter into Application_Start event of
Global.asax.cs file:
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
Controller level
By putting your filter on the top of the controller name:
[Authorize(Roles="Admin")]
public class AdminController : Controller
{
// Logic goes here
}
Action level
By putting your filter on the top of the action name:
public class UserController : Controller
{
[Authorize(Users="User1,User2")]
public ActionResult LinkLogin(string provider)
{
// Logic goes here
return View();
}
}
RouteConfig.cs:
This is used to register various route patterns for your Asp.Net MVC
application. Routing plays an important role in an ASP.NET MVC Application
execution flow, it maps request URL to a specific controller action using a
Routing Table. We can define Routing Rules for the engine, so that it can map > incoming URLs to appropriate controller. Routing Engine uses routing rules
that are defined in Global.asax file in order to parse the URL and find out
the path of corresponding controller. We can find the following piece of code > in Application_Start() method of Global.asax file.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
We can find RouteConfig.cs file under App_Start folder. If we follow
this method in RouteConfig class, we will find one default configured
route as follows. Line 3 to 7 is configuring one default route.
public static void RegisterRoutes(RouteCollection routes)
{
1. routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
2.
3. routes.MapRoute(
4. name: “Default”,
5. url: “{controller}/{action}/{id}”,
6. defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
7. );
}
Line 4 : Name for the route. Line 5 : represent URL : Controller,
action followed by id (if any). Line 6 : default controller will be
Home, default action will be Index and Id is optional.
WebApiConfig.cs:
This is used to register various WEB API routes like as Asp.Net MVC, as well as set any addtional WEB API configurations settings.
AuthConfig.cs:
Used to register external authentication providers
for eg. if you want to enable users to log in with credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google, and then integrate some of the functionality from those providers into your web application.
App_start folder has been introduced in Mvc4. It contains various configurations files like as :
BundleConnfig.cs,
FilterConfig.cs,
RouteConfig.cs,
WebApiConfig.cs
for you application.All those settings are registered within App_Start method of Global.asax.cs file
BundleConfig.cs:
This is used to create and register bundles for CS and JS files.By default various bundles are added in this file including jQuery,jQueryUI,jQuery validation,Modernizer and Site Css..
FilterConfig.cs-
This is used to create and register global MVC filter error filter,action filter etc.By default it contains HandleErrorAttribute filter.
RouteConfig.cs-
This is used to register various route patterns for your Asp.Net MVC application. By default,one route is registered here named as Default Route.
WebApiConfig.cs-
This is used to register various WEB API routes like as Asp.Net MVC,as well as set any additional WEB API configurations settings.
In the previous versions of MVC, we just have RegisterRoutes() method in global.asax file to configure the routing. MVC 4 has built in templates to develop mobile web applications, web apis(restful http services).so to configure the routings for all those template driven development ,we will be using the
AuthConfig.cs(Authorization),BundleConfig.cs(web potimization),,FilterConfig.cs,RouteConfig.cs,WebApiConfig.cs(WEB API) files and they will be mainteained in App_start folder.
Lets have a look at each those config.cs files.
AuthConfig.cs - settings in this file allows you to login to ASP.NET MVC site using third party client credentials like fb account,google account,yahoo account etc..or you can register also.
BundleConfig.cs: settings in this file allows to improve the performance of an applications using bundling...
WebApiConfig: sets the routing settings for WEB API (Note:No action needed in url)
AuthConfi g.cs: Used to confi gure security settings, including sites for OAuth login.
BundleConfi g.cs: Used to register bundles used by the bundling and minifi cation
system. Several bundles are added by default, including jQuery, jQueryUI, jQuery
validation, Modernizr, and default CSS references.
FilterConfi g.cs: Unsurprisingly, this is used to register global MVC fi lters. The only
fi lter registered by default is the HandleErrorAttribute, but this is a great place to put
other fi lter registrations.
RouteConfi g.cs: Holds the granddaddy of the MVC confi g statements, Route confi
guration.
WebApiConfi g.cs: Used to register Web API routes, as well as set any additional Web
API confi guration settings.
All those settings are registered within the App_Start method of Global.asax.cs file
BundleConfig.cs:
This is used to create and register bundles for CS and JS files that we have in the template.
FilterConfig.cs-
This is used to create and register global MVC filter error filter
RouteConfig.cs-
This is used to register various route patterns for your Asp.Net MVC application.
WebApiConfig.cs-
This is used to register various WEB API routes like want login with credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google,

RavenDB in embedded mode - Raven Silverlight Studio (Raven.Studio.xap) not working

I have a small console application doing some persistence with Raven which is working fine, but I just can't get the Raven Studio Web-App working.
I think I have read every article/blog post on the web which is around, but I haven't got it working.
The project is referencing the Raven.Client.Embedded, Raven.Client.Lightweight and Raven.Storage.Esent assemblies)
Here is the really simple code starting up my console app:
class Program
{
static void Main(string[] args)
{
EmbeddableDocumentStore store = new EmbeddableDocumentStore { DataDirectory = #"C:\temp\ravendata", UseEmbeddedHttpServer = true };
store.Initialize();
Console.WriteLine("Initialized");
while (true)
{
string line = Console.ReadLine();
if (line == "w")
{
Changeset cs = CreateChangeset();
using (var session = store.OpenSession())
{
session.Store(cs);
session.SaveChanges();
}
Console.WriteLine("Written.");
}
}
The question is: Where to put the Raven.Studio.xap in order to get it running in the browser (http://localhost:8080/Raven/studio.html)?
It's not working in the bin/debug output folder of my console app (which would be the most logical area where it should be), as well as it isn't if I put it in the root of my console application.
Sorry to ask this thing again, but it seems there is some point I am missing on this to get it up and running. ;)
Thanks for your help, R's, Rene
You are right, I've tried it using a new console application project and had the same issues, altough I copied the file Raven.Studio.xap into the \bin\debug AFTER I had seen the error message for the first time.
I found out, that the reason for this has to do with browser-caching. Even though the file would be available now, the embedded http-server returns 304 Not Modified, because it had sent the If-None-Match header into the request. Therefore, the cached "not-found" page in the browser cache will be used.
I fixed it and sent a patch to Ayende. However the solution now is:
1) make sure Raven.Studio.xap is under \bin\debug
2) clear the browsers cache