Using Routing in Asp.Net Webform Application - asp.net

I am using System.Web.Routing in the Asp.Net Webform Application. I wrote the following route in the global.asax
routes.RouteExistingFiles = true; // I made true/false both, but none works
routes.Add("competition", new Route
(
"Test",
new CustomRouteHandler("~/Test/WebForm1.aspx")
));
And the directory structure is the following:-
Application
|
|--- Test (Folder)
|--- Webform1.aspx
When I write in the browser http://localhost:xxxx/Test/ (using Casini), the request is handle in the traditional manner not through the routes, and, it gives me the "Directory Listing -- /test/" page.
Could you please help me out?

I had the same problem, and I chose the pragmatic solution that the file that should handle the default path is called Default.aspx
routes.Add("competition", new Route ( "Test", new CustomRouteHandler("~/Test/Default.aspx") ));

Are you using Routing straight out the box for WebForms, I have just implemented this for "WebForms" specifically, since there is some things to be aware of:
http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx
HTH
Update:
Using the implementation in the link still produces the same error, since the actual folder exists.
I would think that since the folder exists, it would be served (in some cases listing the folder contents may be desired)
Maybe taking a different approach would be better for instance, if the pages all point to specific extranet login pages maybe an extra descriptive folder would work, eg: /Extranets/Test/ ?

Related

Best practice to create robots.txt file inside my asp.net mvc web site

I want to create a robots.txt for my asp.net mvc-5 web site, now I find this link which talks about achieving this task:-
http://rehansaeed.com/dynamically-generating-robots-txt-using-asp-net-mvc/
where in this link they are creating a separate Controller & Route rule to build the robots.txt ,,,so I am not sure why i can not just create the robot.txt file and add it to the root of my web site as follow:-:-
where if I navigate to the following URL http://www.mywebsite.com/robots.txt the text content will be shown ,without having to create separate controller for this?
so my question is if it is valid to add the robots.txt directly to my web site root without having to do so inside a controller and separate route rule , to keep things simpler ??
On my website, asp net core 3.1, I just used the below simple action:
[Route("/robots.txt")]
public ContentResult RobotsTxt()
{
var sb = new StringBuilder();
sb.AppendLine("User-agent: *")
.AppendLine("Disallow:")
.Append("sitemap: ")
.Append(this.Request.Scheme)
.Append("://")
.Append(this.Request.Host)
.AppendLine("/sitemap.xml");
return this.Content(sb.ToString(), "text/plain", Encoding.UTF8);
}
If you need to dynamically generate the content, then that makes sense because it would give you that ability. But otherwise, I use a robots.txt file in my applications with no problems.
Placing a robots.txt file in the MVC application root as shown in your screenshot, the same place as Startup.cs, worked well for me.

Asp .Net MVC 5 Folder name and Routing conflict

I have an annoying problem with folder names and routes in ASP .NET Mvc 5,
This is the default routes I'm using:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Site", action = "Index", id = UrlParameter.Optional }
);
And I'm also using a custom view engine to map views to the root folder instead of ~/Views so I can have HTML/CSS/JS files organized in a way my team can handle.
The problem is: When I call /Backoffice/Index it goes normally and executes action Index in controller Backoffice, all fine, but when we call /Backoffice, I expected it to presume the action index (by the route configuration), but instead, IIS seems to believe I'm trying to access the folder /Backoffice and gives me a 404 error instead of executing Backoffice::Index().
How can I configure IIS to behave in the intended way in this case? Or, is it really the only best way to keep views in a specific folder?
I did some research and used info from the comments and answers here and got to learn something about how MVC routes work and how IIS handles that.
When we set
routes.RouteExistingFiles = true;
The MVC runtime will ignore every file in the folder and start using the routes and URIs solely to look for controllers and actions, this means by calling /SomeContent it will search for a controller named Somefolder instead of a folder. Then we can configure to serve static content by telling MVC runtime to ignore some specific URI formats:
routes.IgnoreRoute("SomeContent/CSS/{filename}.min.css");
routes.IgnoreRoute("SomeContent/JS/{filename}.min.js");
This causes MVC to ignore URIs that match this pattern and leave it for IIS to resolve what to do with it, then IIS will look out on Web.Config rather there are configurations set to serve this kind of static content and what handler to use and proceeed as usual.
Using this configuration can bring MVC to a whole new level of control where you explicitly define which URI patterns serve static content, everything else explicitly calls an action on a controller, all URIs get to be firstly processed by MVC runtime. I sure wish someone correct me in this last statement if I get it wrong.
MVC routes certain actions based on whether they exist on disk. If you have a folder /BackOffice at the root level, then this appears to be a complication that MVC is going to have issues working around (I knew files were directly routed if they existed; I didn't realize folders were something the framework checked too). Consider renaming the folder or the controller to something else so you don't have this naming conflict. That is a problem with "by convention" approaches....

Custom Folder Structure in ASP.NET MVC 5

I'm trying to determine if it is possible (or practical) to implement Uncle Bob's Screaming Architecture in ASP.NET MVC 5 rather than using the default folder structure.
Here's a link to a description of the Screaming Architecture: http://blog.8thlight.com/uncle-bob/2011/09/30/Screaming-Architecture.html
A hypothetical folder structure would look something like this:
Root
Customers
Controllers
CustomerController.cs
Models
Customer.cs
Views
Index.cshtml
Details.cshtml
Update.cshtml
Employees
Controllers
EmployeesController.cs
Models
Employee.cs
Views
Index.cshtml
Details.cshtml
Update.cshtml
Shared
Views
_Layout.cshtml
Error.cshtml
_ViewStart.cshtml
Web.config
The corresponding URL routes would look like this:
http://www.example.com/customers/ => Customer Index
http://www.example.com/customers/details/1 => Customer Details
http://www.example.com/customers/update/1 => Customer Update
http://www.example.com/employees/ => Employee Index
http://www.example.com/employees/details/1 => Employee Details
http://www.example.com/employees/update/1 => Employee Update
I've created a custom RazorViewEngine and added the appropriate view location formats (e.g. "~/{1}/Views/{0}.cshtml") and partial view location formats (e.g. "~/Shared/Views/{0}.cshtml"). I've also moved the shared _ViewStart.cshtml to the root and merged the Views/Shared folder's web.config with the root-level web.config to avoid having to duplicate these two files in all of the View folders.
Everything works great, however, if I try navigating to an index page (e.g. http://www.example.com/employees/) I get a 403.14 Error (Forbidden). All other routes (including http://www.example.com/employees/index) work just fine.
My guess is that IIS is explicitly blocking the route to the controller's index method because the URL coincides with a folder in the filesystem and directory browsing is disabled by default. If I enable directory browsing, however, it actually takes me to the actual directory listing rather than routing to the controller's index method.
I can move the Customers and Employees folders into a subfolder (i.e. move them out of the root) and everything works fine, but I'd like to try to keep these folders at the top level (per the Screaming Architecture guidelines).
Does anyone have a solution for this issue?
Please note that MVC Areas is not the solution I'm looking for as it does not allow for the folder structure described above (i.e. top-level folders named after high-level use cases and views contained directly within the Views folder rather than in a subfolder).
I'm betting you are right about IIS then. If you have two paths mapped to the same resource, the physical path is checked first on the IIS side.
I was digging around the routes configuration and found the property RouteExistingFiles on RouteCollection and think this could work.
I set the value to true and tested locally with an empty folder in the project, a route redirecting to Home/Index, and navigating to localhost:xxx/MyFolder. It worked correctly.
So then all you should need to do is set this property to true for it to choose Asp.net routes first instead of physical routes.

Cannot route static files in ASP.NET WebForms

We have legacy code to maintain and, to solve a specific customer customization problem, we want to route calls to some files to other files. That is, when the app calls a particular ASPX, it will end up hitting another ASPX.
If you call:
www.foo.com/admin/admin.aspx
It will actually hit:
www.foo.com/customizations/customer1/admin/admin.aspx
This is not a good design but this is legacy code. We just want to solve this.
We are using the System.Web.Routing framework to solve it. This works fine when you set RouteExistingFiles to true, except for static files (CSS, JavaScript and Images).
When I first tried it, it retrieved this error:
There is no build provider register for the extension '.css'.
So I did register a build provider in the web.config file for the .css extension. I used this build provider: PageBuilderProvider because someone recommended it in the internet.
It works! But the CSS is being served with text\html content type.
How do I achieve this?
TL;DR: I want to use routes in ASP.NET Web Forms to make a call for a specific CSS file to actually retrieve another one. A customer needs this for customization.
Try coding a HttpHandler. I had to do something similar but for PDF files, I coded a custom HttpHandler in the end - works very well. You can even set the content type in the HttpHandler code and have a pattern matched path the handler will be used for in the web.config. You can also configure it in web.config not to execute if the path does not point to an existing file e.g. so a 404 is returned without having to code that in the handler itself. I can't post my code (VB.NET) ATM because I'm using a tablet but google search for tutorials. You will also probably need to use the TransmitFile function to actually write out the css file. Is it a web forms project or web site? If its a web site there is a special way of registering the HttpHandler in the web.config.

Allowing file extensions in MVC3

Hello fellow programmers
I am sitting trying to do something with MVC3. Just exploring the library. Not doing anything fancy. I have created a project and a controller. Now I am trying to let MVC3 to allow me to do fx http://localhost/MyController.json, http://localhost/MyController.xml or just http://localhost/MyController. In the .json and .xml examples I get errors. The third is of course allowed. I have tried to google this, but I do not get anything that helps me.
Can anyone here tell me how to allow file extension in MVC3?
Thanks.
EDIT
I have not made any changes to the IIS like mapped file extensions.
You should add a route that includes an extension:
routes.MapRoute("ExtensionRoute",
"/{controller}.{extension}",
new { action="Index", extension = UrlParameter.Optional
);
This example maps the extension to a parameter in the action.
You can also make a route with a hard-coded extension.

Resources