Telling ASP.NET MVC 4 not to route static images - CSS, JS, ICO and ZIP files - asp.net-mvc

I thought I'd got all my routing sorted! Just one little glitch to sort out, but first I need to explain our set-up.
I decided against a catch-all router, and instead am trapping HTTP errors in my web.config file (this question helped). First I turned the old-fashioned CustomErrors off:
<!--<customErrors mode="Off" />-->
Then I turned HTTP error-trapping on:
(as often happens, I couldn't seem to insert this as script). In the interests of full disclosure, my web.config file includes this:
I'm not trapping any application errors in Global.asax.cs. This all works fine - I then have a router which picks up on 404 errors:
routes.MapRoute(
"Error 404",
"Error/MissingPage404",
new { controller = "Error", action = "MissingPage404" }
);
and another for 500 errors:
routes.MapRoute(
"Error 500",
"Error/ServerError500",
new { controller = "Error", action = "ServerError500" }
);
My question is: how can I stop static files being trapped by this? I've already solved the problem for images, thanks to this question, which is to include these lines at the top of my routing config file:
routes.IgnoreRoute("{*allfiles}", new { allfiles = #".*\.(gif|jpg|png|ico)" });
However, the equivalent doesn't work for .js, .ico, .css or .zip files. I tried from another site:
routes.IgnoreRoute("{*allaspx}", new { allaspx = #".*\.css(/.*)?" });
routes.IgnoreRoute("{*allaspx}", new { allaspx = #".*\.ico(/.*)?" });
but that did nothing either. Again in the interests of disclosure, I've got this line at the top of the routing config file, but my understanding is that this only affects files which are found:
routes.RouteExistingFiles = true;
Can anyone help? It seems like MVC is brilliantly thought out, right up until the point of making routing easy to understand and implement.
Many thanks in advance
Andy

Related

wwwroot serving pages not MVC6

I am currently working on an Asp.Net 5 / mvc 6 app. I was running the beta5 release and updated to beta7. I have noticed my index page is loading from the wwwroot directory (I started the app with an index page in the wwwroot and am now using mvc, making the index in the wwwroot redundant)
All of my mvc views were loading correctly prior to the update to beta7, I ideally do not want to go back to beta5.
I have included mvc in the Startup.cs
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",//optional id
defaults: new { controller = "App", action = "Index" }
);
});
Project.json
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-beta7",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta7",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta7",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta7",
"Microsoft.Framework.Configuration.FileExtensions": "1.0.0-beta8",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
},
So after upgrading to beta8 and running dnvm upgrade this has resolved my issue. I believe my configuration was not entirely in line. Thanks to meligy & juergen-gutsch for their answers, very useful to know.
In your Startup class ("Startup.cs" file under src/project-name), in the Configure() method, this line:
app.UseStaticFiles();
probably comes before:
app.UseMvc(routes => ... );
You can change the order so that UseMvc(...) comes before UseStaticFiles(...), but note that this means MVC will try to handle all requests to images etc as well even if it doesn't need to.
You can also just change-the-name-of / move / remove the index file now that don't need it anyway.
Create a complete new ASP.NET 5 project and compare the project.json and the startup.cs with that files from your updated project.
This is the best option to see what is wrong with your current configuration.

CKEditor image dialog is failed

I worked with CKEditor on my .Net Mvc4 project. On localhost all works well, but after publishing project to server is not initialising:
"Uncaught TypeError: Cannot set property 'dir' of undefined"
I fixed this by adding code line before editor initialization:
CKEDITOR.basePath = '//some url/ckeditor/'
After that, the ckeditor is working but refusing to open image upload dialog:
error in ckeditor plugins image.js
Uncaught Error: [CKEDITOR.dialog.openDialog] Dialog "image" failed when loading definition.
There is no any changes in my ckeditor folder. The version is: 4.4.5
Any solutions please?
Check the "Network" tab in your browser for HTTP 404 errors. It looks like the file that contains Image Dialog definition is not available. Either it is not present (e.g. has been accidentally removed) or you have some weird url rewrite issues.
Check in your CKEDITOR.basePath plugins folder image plugin is in there, if not then add it and wala working like a charm ! hope it helps !
Issue
You are getting the error from only including the ckeditor.js (or ckeditor4.js since 4.13) file on server, with this error becoming raised when CKE attempts to load other features such as plugins and languages but cannot find these files in the basepath folder. You can confirm this from the network tab in browser devtools, as CKE attempts to load features, then cannot find them.
Option 1: Link to a CDN Bundle
CKE offers 3 primary bundles (basic, standard, full) which offer a choice between features and page load. More info here.
Option 2: Include Necessary Files
Make the extra files available on your server.
Here's a gulp task which bundles everything from the ckeditor node module folder (excluding the sample).
gulp.task("copy-ckeditor", function () {
// Check and copy languages in config.ckEditorLanguages
var isIncluded = function(path) {
var found = false,
lang = path.split('lang')[1];
if (lang) {
for (var i in config.ckEditorLanguages) {
if (lang.indexOf(config.ckEditorLanguages[i]) != -1) {
found = true;
}
}
}
return found;
},
copyFile = function(stream) {
stream.pipe(gulp.dest(config.buildPath.js + "lib/ckeditor"));
};
return gulp.src([
"node_modules/ckeditor/**/*.*",
"!node_modules/ckeditor/samples",
"!node_modules/ckeditor/samples/**/*"
])
.pipe(foreach(function(stream, file){
if (file.path.indexOf("lang") != -1) {
if (isIncluded(file.path)) {
copyFile(stream);
}
} else {
copyFile(stream);
}
return stream;
}));
});
Option 3: Build and Host Your Own Custom Bundle
If you want to use a single file load, you can use the CKE4 Builder allowing you to customise built-in plugins.

VS2013 Browser Link "The controller for path '/9ac086a69364466a841e03e001f946fd/arterySignalR/ping' could not be found."

Since updating to VS2013, we receive this error when running our (MCV4) web app:
The controller for path '/9ac086a69364466a841e03e001f946fd/arterySignalR/ping' could not be found.
I know that it relates to browser link although i'm not sure what we need to do to make it work correctly. Is there some configuration change we need to make to support this new feature?
I disabled browser link. Second #4 at this link.
http://blogs.msdn.com/b/webdev/archive/2013/06/28/browser-link-feature-in-visual-studio-preview-2013.aspx
If you would like the benefit of Browser Link but don't want the missing controller path exceptions, you can add an ignore regex to your route collection. This is what I did:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
#if DEBUG
routes.IgnoreRoute("{*browserlink}", new { browserlink = #".*/arterySignalR/ping" });
#endif
//...
}
The regex technique is courtesy of this Phil Haack post.
On VS2013 #Todd's solution didn't work for me, so I made my own.
Hope it saves you some time.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
#if DEBUG
routes.IgnoreRoute("{*browserlink}", new { browserlink = #".*__browserLink.*" });
#endif
}
Add the following to your root web.config:
<appSettings>
<add key="vs:EnableBrowserLink" value="false" />
</appSettings>
This happens to be a known issue with SignalR and has been fixed in SignalR 2.0.1 and 1.1.5:
2.0.1: https://github.com/SignalR/SignalR/issues/2569 (not yet released)
1.1.5: https://github.com/SignalR/SignalR/issues/2570 (not yet released)
Long story short, nothing you can do to change it, should just wait for the next release of browser link which has a newer version of SignalR.
Had in VS2013, after some project nuget package updates.
Cleaned the solution, closed VS and IISExpress from try and resolved

Modal Views - internal page not loading

I have read through the documentation and hopefully I am just missing the correct "file://" url syntax (or relative path) for forge (forge://).
My src directory contains a local file named noconnection.html. My js directory contains a javascript file with the following code:
if (forge.is.connection.connected()) {
// do cool stuff
} else {
forge.tabs.open("noconnection.html");
}
Command line:
(forge-environment) forge run android
The modal "pops" up just fine (and has the little close button). However, the page has a big "web page not available" error - the web page noconnection.html might be temporarily down or it may have moved.
I have tried these without success to correctly display my simple "no connection" modal:
forge.tabs.open("/noconnection.html");
forge.tabs.open("../noconnection.html");
forge.tabs.open("file:///noconnection.html");
forge.tabs.open("forge:///noconnection.html");
Anyone have any idea what I am doing wrong? Relative path? Thanks in advance.
To get the path to the local page, you need to use the forge.tools.getURL method like this:
if (forge.is.connection.connected()) {
// do cool stuff
} else {
forge.tools.getURL('noconnection.html', function(path) {
forge.tabs.open(path);
});
}

Deploying asp.net mvc iis6.0 how to change route TO include .aspx

This is my routing tables where do I put the various '.aspx' registrations?
//Turns off the unnecessary file exists check
this._Routes.RouteExistingFiles = true;
//Ignore text, html, xml files.
this._Routes.IgnoreRoute("{file}.txt");
this._Routes.IgnoreRoute("{file}.htm");
this._Routes.IgnoreRoute("{file}.html");
this._Routes.IgnoreRoute("{file}.xml");
//Ignore axd files such as assest, image, sitemap etc
this._Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Ignore the assets directory which contains images, js, css & html
this._Routes.IgnoreRoute("Assets/{*pathInfo}");
//Ignore the error directory which contains error pages
this._Routes.IgnoreRoute("ErrorPages/{*pathInfo}");
//Exclude favicon (google toolbar request gif file as fav icon)
this._Routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });
//Photo routes
this._Routes.MapRoute("PhotoAssets", "Photos/Photo/{photoId}/Size/{photoSizeClassificationId}", MVC.Photo.Photo(0, null));
//Handles department profile routes
this._Routes.MapRoute("WorkerProfileLeader", "Department/{departmentId}/Worker/Profile/Leader/List/{viewType}", MVC.WorkerProfile.List(PersonType.Leader, "", DisplayViewType.SummaryThumbnailList));
this._Routes.MapRoute("WorkerProfile", "Department/{departmentId}/Worker/Profile/{personType}/List/{viewType}", MVC.WorkerProfile.List(PersonType.Pleb, "", DisplayViewType.ThumbnailGrid));
this._Routes.MapRoute("WorkerProfilePerson", "Department/{departmentId}/Worker/Profile/{personType}/Detail/{personId}", MVC.WorkerProfile.Detail(PersonType.Pleb, "", ""));
//Default route mapping
this._Routes.MapRoute("Start", "Default.aspx", MVC.Home.Index());
this._Routes.MapRoute("Default", "{controller}/{action}", MVC.Home.Index());
Cheers
Anthony
Just make sure the first part or the URL ends with .aspx like:
this._Routes.MapRoute("WorkerProfileLeader", "Department.aspx/{departmentId}/Worker/Profile/Leader/List/{viewType}", ...
this._Routes.MapRoute("Default", "{controller}.aspx/{action}", MVC.Home.Index());
I'm pretty sure it in fact doesn't matter where in the URL the .aspx is as long as it's somewhere in there and is the first thing that appears to be a file extension. In fact, one trick I've seen is to put the .aspx in the folder name containing the application! In other words, the application name itself would be "myapp.aspx" even though that's just a folder.
As long as .aspx appears as the first file extension in the path IIS will use that file extension to handle the request.

Resources