asp.net 4.0 web forms routing - default/wildcard route - asp.net

I there a simple way when using ASP.NET 4.0 routing with Web Forms to produce a route that will act as some kind of wildcard?
It seems to me that within WebForms, you have to specify a route for every page - I am looking for some kind of generic route that can be used where nothing specific is required, perhaps mapping directly from path to path so...
http://somedomain.com/folder1/folder2/page would possibly map to folder1/folder2/page.aspx
Any suggestions?
Thanks

You can match all remaining routes like this:
routes.MapPageRoute("defaultRoute", "{*value}", "~/Missing.aspx");
In this case, we know all routes, and want to send anything else to a "missing"/404 page. Just be sure to put this as the last route, since it is a wildcard and will catch everything.
Alternatively you could register a route the same way, but internally does mapping to a page, like this:
routes.Add(new Route("{*value}", new DefaultRouteHandler()));
That handler class would do your wildcard mapping, something like this:
public class DefaultRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//Url mapping however you want here:
var pageUrl = requestContext.RouteData.Route.Url + ".aspx";
var page = BuildManager.CreateInstanceFromVirtualPath(pageUrl, typeof(Page))
as IHttpHandler;
if (page != null)
{
//Set the <form>'s postback url to the route
var webForm = page as Page;
if (webForm != null)
webForm.Load += delegate { webForm.Form.Action =
requestContext.HttpContext.Request.RawUrl; };
}
return page;
}
}
This is broken a bit in odd places to prevent horizontal scrolling, but you get the overall point. Again, make sure this is the last route, otherwise it'll handle all your routes.

Additionally - Keep in mind that you need to add an exception for the .axd files in your Global.asax file if there are validation controls in your web app:
http://basgun.wordpress.com/2010/10/25/getting-syntax-error-in-asp-net-routing-due-to-webresource-axd/
Otherwise, you will keep getting a syntax error because the routing picks up the .axd files and not properly loads the JavaScript files needed for the validation controls.

Related

Umbraco and dynamic URL content at root level

I need to port a website to asp.net and decided to use Umbraco as the underlying CMS.
The issue I'm having is I need to retain the URL structure of the current site.
The current URL template looks like the following
domain.com/{brand}/{product}
This is hard to make a route for since it mixes in with all the other content on the site. Like domain.com/foo/bar which is not a brand or product.
I've coded up a IContentFinder, and injected it into the Umbraco pipeline, that check the URL structure and determins if domain.com/{brand} matches any of the known brands on the site, in which case i find the content by its internal route domain.com/products/ and pass along {brand}/{model} as HttpContext Items and return it using the IContentFinder.
This works, but it also means no MVC controller is called. So now I'm left with fetching from the database in the cshtml file which is not so pretty and kind of breaks MVC conventions.
What i really wan't is to take the url domain.com/{brand}/{product} and rewrite it to domain.com/products/{brand}/{product} and then being able to hit a ProductsController serving up the content based on the parameters brand and product.
There are a couple of ways to do this.
It depends a bit on your content setup. If your products exist as pages in Umbraco, then I think you are on the right path.
In your content finder, remember to set the page you've found on the request like this request.PublishedContent = content;
Then you can take advantage of Route Hijacking to add a ProductController that will get called for that request: https://our.umbraco.org/Documentation/Reference/Routing/custom-controllers
Example implementation:
protected bool TryFindContent(PublishedContentRequest docReq, string docType)
{
var segments = docReq.Uri.GetAbsolutePathDecoded().Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
string[] exceptLast = segments.Take(segments.Length - 1).ToArray();
string toMatch = string.Format("/{0}", string.Join("/", exceptLast));
var found = docReq.RoutingContext.UmbracoContext.ContentCache.GetByRoute(toMatch);
if (found != null && found.DocumentTypeAlias == docType)
{
docReq.PublishedContent = found;
return true;
}
return false;
}
public class ProductContentFinder : DoctypeContentFinderBase
{
public override bool TryFindContent(PublishedContentRequest contentRequest)
{
// The "productPage" here is the alias of your documenttype
return TryFindContent(contentRequest, "productPage");
}
}
public class ProductPageController : RenderMvcController {}
In the example the document type has an alias of "productPage". That means that the controller needs to be named exactly "ProductPageController" and inherit the RenderMvcController.
Notice that it does not matter what the actual pages name is.

How to convert url path to full or absolute url in ASP.NET MVC?

I am developing Web Application using ASP.NET MVC in C#. But I am having a problem with retrieving full or absolute url. In ASP.NET MVC we get url like this. Url.Content("~/path/to/page"). It will return "path/to/page". But what I want to do is I have a string like this - "~/controller/action".
Let's consider my website domain is www.example.com. If I use Url.Content("~/controller/action"), it will just return "controller/action". I want to get "www.example.com/controller/action". How can I get it?
If you can use the Controller / Action Names...
You should use the Url.Action() method for this.
Typically, Url.Action() will return something similar to what you presently expect when provided with just the Controller and Action names :
// This would yield "Controller/Action"
Url.Action("Action","Controller");
However, when you pass in the protocol parameter (i.e. http, https etc.) then the method will actually return a complete, absolute URL. For the sake of convienence, you can use the Request.Url.Scheme property to access the appropriate protocol as seen below :
// This would yield "http://your-site.com/Controller/Action"
Url.Action("Action", "Controller", null, Request.Url.Scheme);
You can see an example of this in action here.
If you only have a relative URL string...
If you only have access to something like a relative URL (i.e. ~/controller/action), then you may want to create a function that will extend the current functionality of the Url.Content() method to support serving absolute URLs :
public static class UrlExtensions
{
public static string AbsoluteContent(this UrlHelper urlHelper, string contentPath)
{
// Build a URI for the requested path
var url = new Uri(HttpContext.Current.Request.Url, urlHelper.Content(contentPath));
// Return the absolute UrI
return url.AbsoluteUri;
}
}
If defined properly, this would allow you to simply replace your Url.Content() calls with Url.AbsoluteContent() as seen below :
Url.AbsoluteContent("~/Controller/Action")
You can see an example of this approach here.
The following will render a full url, including http or https:
var url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
var fullUrl = url.Action("YourAction", "YourController", new { id = something }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);
Output
https://www.yourdomain.com/YourController/YourAction?id=something

How to create an ASP.NET route that redirects to a path that uses part of the route?

I want to create a route that redirects all requests matching certain pattern to a location built using parts of the pattern. I want to grab some segment in the URL and treat the rest like a path to an aspx page in Web Forms application. For example
RouteTable.Routes.MapPageRoute("SomeRouteName", "{something}/{*path}", "~/pages/{*path}/Default.aspx");
Where *path could be something contain "\". The query string should be preserved as a query string.
Is it possible to create souch a route?
I don't know of any way to do it that way.
The more standard way would be to set the target as "~/pages/default.aspx" and then have that page check for the {path} argument and display the corresponding data.
If you really want it in another path, then don't use a {} placeholder. Simply hard code that section of the path (both the source and target).
After looking at several ways to do this I ended up creating my own routing handler that is something like this:
public class SomethingRoutingHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string something = (string)requestContext.RouteData.Values["something"];
string path = (string)requestContext.RouteData.Values["path"];
string virtualPath = "~/" + path + "Default.aspx";
return BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page)) as Page;
}
}
I then use the RouteData in the pages to access something. I found these articles helpful:
http://msdn.microsoft.com/en-us/magazine/dd347546.aspx
http://www.xdevsoftware.com/blog/post/Default-Route-in-ASPNET-4-URL-Routing.aspx

How to prevent user from direct url entering

I am using ASP.NET 4.0 Framework.I have a directory which contains 10 PDF files i.e pdf1,pdf2....pdf10. On button click i am using Response.Redirect & passing Pdf file path in order to open it in the browser. but, this enables user to view the path(url) of the PDF folder using this url he can open any other pdf directly. How can i stop him accessing PDF directly from the url
Use Request.ServerVariables["HTTP_REFERER"] this will tell you where the request had come from. If its not on your site then take appropriate action.
e.g.
if(Request.ServerVariables["HTTP_REFERER"].ToLower().IndexOf("mysite.com") == -1){
// Not from my site
Response.Redirect("NotAllowed.aspx");
}
This link may help you to stop him accessing PDF directly from the url.
Use this code in Global.asax.cs and Call [NoDirectAccess] to all controllers
//Prevent direct URL access: Call [NoDirectAccess] to all controllers to block
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class NoDirectAccessAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.UrlReferrer == null ||
filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Home", action = "Login", area = "" }));
}
}
}
You will need to add a secure layer. If you are using MVC it will probably be simpler to implement since you will do the authorisation in the controller action. However, for classic ASP you will probably need to implement a custom handler.
There is no easy solution to this. You could devise some sort of rolling code based on the server date/time that must be part of the query string and check for the correctness of this in the page load, if you make it sufficiently complicated / long, then people will not be able to enter this manually.

How to use System.Web.Routing to not URL rewrite in Web Forms?

I am using System.Web.Routing with ASP.NET (3.5) Web Forms that will URL rewrite the following URL from
http://www.myurl.com/campaign/abc
to
http://www.myurl.com/default.aspx?campaign=abc
The code is as below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add("CampaignRoute", new Route
(
"{campaign_code}",
new CustomRouteHandler("~/default.aspx")
));
}
IRouteHandler implementation:
public class CustomRouteHandler : IRouteHandler
{
public CustomRouteHandler(string virtualPath)
{
VirtualPath = virtualPath;
}
public string VirtualPath { get; private set; }
public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
if (requestContext.RouteData.Values.ContainsKey("campaign_code"))
{
var code = requestContext.RouteData.Values["campaign_code"].ToString();
HttpContext.Current.RewritePath(
string.Concat(
VirtualPath,
"?campaign=" + code));
}
var page = BuildManager.CreateInstanceFromVirtualPath
(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
However I noticed there are too many things to change on my existing aspx pages (i.e. links to javascript, links to css files).
So I am thinking if there's a way to keep above code but in the end rather than a rewrite just do a Request.Redirect or Server.Transfer to minimize the changes needed. So the purpose of using System.Web.Routing becomes solely for URL friendly on the first entry.
How to ignore the rest of the patterns other than specificed in the code?
Thanks.
Using rewriting combined with ASP.NET URL Routing is not recommended because some implementations of ASP.NET URL Routing internally use rewriting as well (it depends on the version of ASP.NET). The combination of two different components using rewriting can cause conflicts (though I'm not 100% sure that that's why you're seeing this problem).
Regarding using transfer/redirect/rewrite:
My strongest recommendation would be to not use any of them! Instead of redirecting (or anything else) just let the page be called directly by ASP.NET by returning it from the IRouteHandler, much as you are already doing (just without the call to Rewrite). As long as your IRouteHandler saves the RouteData somewhere, the Page can then get the data from the route and you should be good to go.
Take a look at Phil Haack's Web Form routing sample to see an example of how to save the route data (or just use his code!).
Regarding ignoring patterns:
You can use an IRouteConstraint to constrain which URLs match your route. There is a built-in default route constraint implementation that uses regular expressions, but you can also write custom route constraints. Here is an example:
Route r = new Route(...);
r.Constraints = new RouteValueDictionary(new {
campaign_code = "\d{5}", // constrain to 5-digit numbers only
other_value = new CustomRouteConstraint(), // call custom constraint
});
CustomRouteConstraint is a class that you can write that derives from IRouteConstraint.
One thing I should note about static files such as CSS and JPG files is that by default they are always excluded from routing. By default routing ignores patterns that exactly match physical files on disk. You can change this behavior by setting RouteTable.Routes.RouteExistingFiles = true, but that is not the default.

Resources