Symfony redirect to dynamic route name - symfony

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.

Related

Get defined Route from Dto

I've created a basic Dto Hit tracker that counts how many times a ServiceStack API is requested. What I'm trying to get now is the Route that was defined for the current Dto in the ServiceBase using Routes.Add. I can get current Url from the HttpContext, however that one is already populated with data. E.g
//Defined Route
/customers/{CustomerID}/orders
//From HttpContext
/customers/123456/orders
Is there way to get the defined route with the parameter {CustomerID} still there?
You can get the Route for the Request with IRequest.GetRoute().
Also if you want to create a Request DTO from a path or URL you can use Metadata.CreateRequestFromUrl() added in the latest v5.1 Release Notes.

Restrict Direct Pathing

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.

Convention-based routing in Symfony2

I'm trying to learn learn how routing works in Symfony2, and so far everything I've read has examples like this:
blog:
path: /blog/{page}
defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
This routes requests to /blog/123 to the AcmeBlogBundle Blog controller's "index" action, and passes the 123 parameter as the "page" parameter to that controller action. If no page parameter is passed, then the page defaults to 1.
That's all well and good, but what if you want to simply have a convention based routing system that passes things through like this:
/{bundle}/{controller}/{action}
So, for a URL like this:
/acme/blog/index
It would then call AcmeBlogBundle Blog controller's "index" action.
No specific routing configuration is necessary, it simply infers the bundle, controller, and action from the URL. So you can continue adding bundles, controllers, and actions, and you don't need to modify the routing configuration. It just works.
If this isn't possible, can you at least infer the controller and action from the URL? E.g., perhaps you need a route that specifically identifies the bundle, but can we get the controller and action from the URL?
I read through the Symfony "The Book" page about routing, and I couldn't figure out a way to do this.
No way. This was considered as bad practice and so it was removed from symfony.
But you should take a look at the #Route annotation, as it simplifies configuring routes in such a nice way. Directly attached to the action, there is no lack between config and code.

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.

URLs for e-mailing in ASP.NET MVC

How would I generate a proper URL for an MVC application to be included in an e-mail?
This is for my registration system which is separate from my controller/action. Basically, I want to send an email verification to fire an Action on a Controller. I don't want to hardcode the URL in, I would want something like the Url property on the Views.
In your Controller, the UrlHelper is just called "Url" - so:
void Index() {
string s = this.Url.Action("Index", "Controller");
}
The "this" is unnecessary, but it tells you where this Url variable comes from
I used:
Html.BuildUrlFromExpression<AccountController>(c=>c.Confirm(Model.confirmedGUID.Value))
It is part of the HTMLHelper (I think in the MVC Futures) so you may have to pass an instance of the HTMLHelper to your service layer, not sure. I use this directly in my view which renders to an email. That gives you the absolute URL and then I store the domain (http://www.mysite.com) in the config file and append it before the URL.
You should probably make the URL part of the configuration of your application.
I know you can do stuff with e.g. the Server property on your web application, but the application will never know if its IP or domain name is reachable from the outside as it might be hidden behind a proxy or a load balancer.
If I'm reading the question correctly, you need to controller/action outside the MVC code. If so, you will need to simply configure the URL in Application Configuration or some such place, unless you have access to the controller classes and use reflection to get the names.

Resources