Restrict Direct Pathing - asp.net

I have a project in VS 2015. There is a page called home-program.aspx.
This is the route I set up for that page:
Dim sDestinationRegExp As String = "^(world|land|line|run|club)${2,}"
routes.MapPageRoute("landing", "destinations/{destination}", "~/home-program.aspx",
True,
New RouteValueDictionary(New With
{.destination = "world"}),
New RouteValueDictionary(New With
{.destination = sDestinationRegExp}))
Now, the route works. However. the user is still able to access that page by using /home-program or /home-program.aspx. Is there a way to prevent them from accessing those pages using those urls and instead use the mapped route instead?

I suspect you can add a "catch-all" route at the tail-end of the route mapping that will map everything to a 403 or 404 page (whatever you think is best).
This answer shows how to create a catch-all route mapping. Make sure it is at the end of the maps -- the last thing you add.
This should prevent the rest of the pipeline modules from trying to process the URLs. Another IIS module (from ASP.NET) will get invoked by default if your route maps don't match a URL. This is how the request for /home-program.aspx gets handled. If you handle it with a route map entry, the default module shouldn't interfere.

Related

Symfony redirect to dynamic route name

I'm using the Symfony CMF Routing Bundle to create dynamic routes (I'm using one example here):
$route = new Route('/dynamic-url');
$route->setMethods("GET");
$route->setDefault('_controller', 'AppBundle:MyRoute:getResponse');
$routeCollection->add('my-dynamic-route', $route);
The response is loaded from the getResponseAction() function inside the MyRouteController:
/**
* No annotations here, because I want the url to be dynamic from the database
*/
public function getResponseAction(Request $request) {
return $this->render('dynamic-page-template.html.twig');
}
When I go to '/dynamic-url', it works.
When in another controller, I want to redirect to this dynamic route, like this:
return $this->redirectToRoute('my-dynamic-route');
But I get this error: "None of the chained routers were able to generate route: Route 'my-dynamic-route' not found"
Also interesting: when I go to '/dynamic-url', the dev bar actually says that the Route name is 'my-dynamic-route'.
Edit
When I load all the routes, I don't see my dynamic route names:
$this->get('router')->getRouteCollection();
I think they should be in this list.
Since it's a dynamic route, which wasn't saved anywhere (like routing.yml ) it will be only availabe for Request where it has been defined. So at the end of Request your app will immediately "forget" about new Route generated at runtime.
When I load all the routes, I don't see my dynamic route names:
$this->get('router')->getRouteCollection();
I think they should be in this list.
Actualy No. It depends on where you call $this->get('router')->getRouteCollection();
Just try to call
dump($this->get('router')->getRouteCollection();)
right before the return statement in your Action where you're adding the my-dynamic-route route. I'm sure you'll see your my-dynamic-route in the list of routes, but if you call it anywhere else - you won't see it.
It's less about symfony rather about stateless nature of web (see Why say that HTTP is a stateless protocol?)
I started to think about this and pointed your question to an routing issue on symfony-cmf. You tagged with #symfony-cmf and i think this would be important feature for us.
I also think, when you persist your route with /my-route you should also ask the router for that name (or in case of the CMF with an content object with that a route.)
If you use the CmfRoutingBundle dynamic router, you should persist your routes to doctrine. The idea of dynamic here is that they can be created at runtime, e.g. in an admin interface or elsewhere by code. The DynamicRouter loads routes from the database.
If you use PHPCR-ODM, the route name is the repository id, typically something like /cms/routes/my-route and you can generate it with that name. If you have access to the route object loaded from the database, you can also generate from that, rather than the path. If you have to hardcode a path in your application, its an indication that probably a normally configured route would be better.
If you just add a route to the route collection on the fly, you would have to make sure that happens in each request, its only available when you add it. With the CMF ChainRouter you could register your own router that does that, but i would not know of a good use case for that. Either you know the route, then you can configure it in the routing.xml|yml|php config file. Or routes are loaded dynamically, in which point you should use DynamicRouter, potentially with a custom route loader.

Html.BeginForm in WebApi - routing

I have a Web API project as part of my solution (also containing an MVC4 project) and within the Api project I am trying to post a form to the Values controller Post method (from a view also within the Api project).
Using Html.BeginForm() or Html.BeginForm("Post", "Values") posts to /Values/Post but I need it to go to /api/Values/Post
Any idea which overload or settings I need to post to the correct location?
I can hit all the action methods fine from fiddler (e.g. localhost/api/values).
You would need to use BeginRouteForm as link generation to Web API routes always depends on the route name. Also make sure to supply the route value called httproute as below.
#using (Html.BeginRouteForm("DefaultApi", new { controller="Values", httproute="true" }))
The API controller uses a different route to the default. It's supposed to be consumed from JS (AJAX) rather than a real form post so there's no obvious support for it in HtmlHelpers. Try:
Html.BeginForm("values", "api")
This would trick it into thinking "values" is the action and "api" is the controller. "Post" is inferred from the http method.

Building querystring in routing webforms .net 4.0

I'm trying out .net 4.0 routing with Webforms for the first time and I'm running into a problem. The page I'm routing to is looking for a querystring based on the route url.
For Example:
routes.MapPageRoute(
"Rule2", // Route name
"news/{day}/{month}/{year}/{.*}.aspx", // Route URL
"~/mynews.aspx" // Web page to handle route
);
I want the final route to send mynews.aspx?story={day}{month}{year}. But I can't figure it out. I found this to be some help http://msdn.microsoft.com/en-us/library/cc668177.aspx but request.querystring("story") gives me nothing.
Any words of wisdom?
Normally you wouldn't have 'aspx' in the route URL because you'd want a user friendly one. So, the route URL would be "news/{day}/{month}/{year}/{.*}" and a valid URL 'news/25/5/2012', for example.
Then to access the data you use
string day = (string) RouteData.Values["day"].

Returning Requested URL within Custom Error Page in ASP.net

Working in ASP.net 3.5 and MVC 1.0.
What I would like to do is return the requested URL, which generates a 404 error, within the custom error page. Much like Google does on their error pages (http://www.google.com/test).
eg.
We're sorry, but the requested address "http://www.domain.com/nonexistantpage.aspx" does not exist on this server.
What would be the best way to accomplish this kind of soft 404?
Also, as a side note: Anyone familiar with returning the custom error page in place of the ugly ...notfound?aspxerrorpath=/awdawd nonsense, while keeping the requested URL in a browser's address bar? ...I suspect something to do with a server.transfer?
Check out these resources related to this topic:
ASP.Net MVC Custom Error Pages
Three common ASP.NET MVC URL routing issues
To summarize, you can accomplish a google-like implementation with keeping the requested URL by defining a catch-all route that executes a particular controller action.
//defined below all other routes
routes.MapRoute(
"Catch All",
"{*path}",
new { controller = "Error", action = "NotFound" }
);
public ActionResult NotFound(string path)
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
ViewData["path"] = path; //or Request.Url.ToString() if you want full url
return View();
}
This is not a complete solution, though. Assuming you've left the default route mapping, anything that matches {Controller}/{action}/{id} is still going to a throw a traditional 404 or custom error. You'd have to explicitly define all possible routes if you truly wanted to have the catch-all route pick up anything that didn't map to a specific controller/action or parameter type - not necessarily a trivial task.

Asp.Net MVC routing diffrence in www.Mysite.com/Employee and www.Mysite.com/Employee/ while using JqGrid

I am using ASP.NEt MVC for one of my project.
In this I have Employee controller which can be called by www.Mysite.com/Employee/ url.
Also I have used JqGrid which uses followng to fetch data
url: "GetGridData"
While testing the same I found that
If i type www.Mysite.com/Employee/ in browser a call is made to
www.Mysite.com/Employee/GetGridData
If i type www.Mysite.com/Employee in browser a call is made to
www.Mysite.com/GetGridData
Note: the missing / at the end in second call.
How to rectify this as the chances are end user can type any of this url in browser.
I'd take a look at how you're asking JqGrid to make it's web service call - because it won't know anything about MVC's routing engine by default - and this is all happening client side.
Stepping outside of MVC for a minute, if I have a page:
example.com/page1.aspx
And have a relative link to another page on there:
Click here
The browser will look for page2.aspx at the same level as page1.aspx, i.e.
example.com/page2.aspx
If I move page1 to a new folder:
example.com/NewFolder/page1.aspx
The browser will ask for
example.com/NewFolder/page2.aspx
when a user clicks on the link.
The same thing is happening to your GetGridData call - these are being made by the web browser to your server based on the information it has available to it.
So if your page responds on:
example.com/Employee
And asks for a relative request to:
GetGridData
The browser will send that request to the same level that Employee appears to be on:
example.com/GetGriddata
Which then fails because the routing engine can't find a route for that request.
You should look at generating the URL for the GetGridData call dynamically through the routing system, which will ensure that it's built as:
url: "/Employee/GetGridData"
Final edit to add
Forgot to mention, you should probably use the UrlHelper Action methods for this:
url: <%=Url.Action("GetGridData")%>
This will generate a path to the GetGridData method on the current controller. If you need to access a different controller, or pass some values, there are overloads to help.
Try debugging your route:
Phil Haack's: ASP.NET Routing Debugger

Resources