how to recover a previous route name of page in symfony - symfony

for example I was on the home page, it has the route name "home", after I left on another page for example edit, how to get the name of the previous route on the edit page (here it is home)? thanks

you can get the referrer and try to "match" it with the routing service to see if a route exists for this path:
$referer = $request->headers->get('referer'); // get the referer, it can be empty!
if (!\is_string($referer) || !$referer) {
echo 'Referer is invalid or empty.';
return;
}
$refererPathInfo = Request::create($referer)->getPathInfo();
// try to match the path with the application routing
$routeInfos = $this->router->match($refererPathInfo);
// get the Symfony route name if it exists
$refererRoute = $routeInfos['_route'] ?? '';
Check out the full snippet on my blog.

Related

MVC controller action causing 404 not found error

NOTE: This is not a duplicate of another question as my first page works fine, it is other pages/actions that are not working.
I've ready many posts so far and nothing comes close. This works just fine when run locally on my development box. After I copy to the server, I see the problem. My default route works fine, I get the expected index page.
public ActionResult Index()
{
return View();
}
My RouteConfig contains:
routes.MapRoute(
name: "AnnualFees",
url: "{controller}/{action}/{id}",
defaults: new { controller = "AnnualFees", action = "Index", id = UrlParameter.Optional }
);
Problems arise when I want to reach anything other than Index. For example, this action causes a 404 not found error:
public ActionResult renderForm()
{
return PartialView("_formPanel");
}
Again, works as it should on my local dev box. But on the server I get Requested URL: /AnnualFees/renderForm 404 error The resource cannot be found.
UPDATE
Ok, doing some more research and trial and error, I discovered something and have a bit more to add.
This app is running under a current website in IIS, where I created a Virtual Folder/application under the website root. If I navigate to www.mysite.com/AnnualFees I get the first page of my MVC app as expected. However, the only way I can get to any other action in my AnnualFeesController, I have to double up the controller name like www.mysite.com/AnnualFees/AnnualFees/renderForm which works but is ugly and not quite right. How can I get rid of the redundancy?
So the problem, as I noted in the comment, is that you have a folder, and under it goes the route. If you do not provide any parts of the route, just calling
www.mysite.com/AnnualFees
this uses all defaults as specified in your route config, and you get the default page. However if you type
www.mysite.com/AnnualFees/ActionName
MVC sees that as controller ActionName and no action no id provided. This does not exist in your app, thus the error.
The root problem here is that websites are not supposed to live under folders, they are supposed to live under top domains. That is, it is not expected that site root URL is www.mysite.com/AnnualFees, it is supposed to be just www.mysite.com. But even that would be fine if you did not have your main controller and IIS folder with the same names, producing unwanted duplication.
You can however change you route to make AnnualFees a default controller. Simply remove the controller part like so:
routes.MapRoute(
name: "AnnualFees",
url: "{action}/{id}",
defaults: new { controller = "AnnualFees", action = "Index", id = UrlParameter.Optional }
);
Now you should be able to use
www.mysite.com/AnnualFees/ActionName
Again, note that in the above URL "AnnualFees" is not a controller name, it is in fact no visible to MVC app at all.
There is however a caveat. Imagine you need to add another controller. Now the default and only route would not work with it. The key is to provide a separate route for this controller, with hardcoded first part
routes.MapRoute(
name: "NewControllerRoute",
url: "NewControllerName/{action}/{id}",
defaults: new { controller = "NewController", action = "Index", id = UrlParameter.Optional }
);
Make sure to put this route before the default one, so that all requests to this controller are routed correctly, and all other requests go to "AnnualFees".

Matching a URL to a route in Symfony

We have files behind authentication, and I want to do different things for post-authentication redirect if the user entered the application using a URL of a file versus a URL of an HTML resource.
I have a URL: https://subdomain.domain.com/resource/45/identifiers/567/here/11abdf51e3d7-some%20file%20name.png/download. I want to get the route name for this URL.
app/console router:debug outputs this: _route_name GET ANY subdomain.domain.{tld} /resource/{id2}/identifiers/{id2}/here/{id3}/download.
Symfony has a Routing component (http://symfony.com/doc/current/book/routing.html), and I'm trying to call match() on an instance of Symfony\Bundle\FrameworkBundle\Routing\Router as provided by Symfony IOC. I have tried with with the domain and without the domain, but they both create a MethodNotAllowed exception because the route cannot be found. How can I match this URL to a route?
Maybe a bit late but as I was facing the same problem, what I come to is something like
$request = Request::create($targetPath, Request::METHOD_GET, [], [], [], $_SERVER);
try {
$matches = $router->matchRequest($request);
} catch (\Exception $e) {
// throw a 400
}
The key part is to use $_SERVER superglobal array in order to have all things setted straight away.
According to this, Symfony uses current request's HTTP method while matching. I guess your controller serves POST request, while your download links are GET.
The route name is available in the _route_name attribute of the Request object: $request->attributes->get('_route_name').
You can do something like this ton get the route name:
public/protected/private function getRefererRoute(Request $request = null)
{
if ($request == null)
$request = $this->getRequest();
//look for the referer route
$referer = $request->headers->get('referer');
$path = substr($referer, strpos($referer, $request->getBaseUrl()));
$path = str_replace($request->getBaseUrl(), '', $lastPath);
$matcher = $this->get('router')->getMatcher();
$parameters = $matcher->match($path);
$route = $parameters['_route'];
return $route;
}
EDIT:
I forgot to explain what I was doing. So basicly you are getting the page url ($referer) then taking out your website's base url with str_replace and then trying to match the remaining part of the path with a know route pattern using route matcher.
EDIT2:
Obviously you need to have this inside you controller if you want to be able to use $this->get(...)

Catching all requests mvc 4

I have a folder with resources and I'd like to give opportunity to all users with right token get access it.Requests like:
www.mysite.com/uploads/images?token = some security value
So I need to handle all requests that starts with
www.mysite.com/uploads
chek for right token and approve or reject request.Could you give a basic example?
Why not just create a route for www.mysite.com/uploads/images/token?
routes.MapRoute(
"Uploads", // Route name
"uploads/images/{token}", // URL with parameters
new { controller = "uploads", action = "images", token = "" } // Parameter defaults
);
}
This route should be placed at top of your route list and would catch route that starts with /uploads... Your users would be routed to uploadsController (in this case) and would execute the images Action Method passing Token as a string parameter.

Redirect to default full URL with mvc3

I want to give the users a friendly URL, with the desired area, and whenever they enter it, the site is forwarded to the default controller/action., but I am having a real hard time figuring out how to do it.
Example: someone types http://mySite.com/System and the routing engine redirects to the complete default url http://mySite.com/System/Auth/SignIn
I tried this, but it isn't working
routes.MapRoute(
"System", // Route name
"System/{controller}/{action}", // URL with parameters
new { area = "System", controller = "Auth",
action = "SignIn", id = UrlParameter.Optional } // Parameter defaults
);
PS: as I am using areas, System in this case is the {area}, Auth is the {controller} and SignIn is the {action}.
Could use a SystemController at the root level of your application, of which the Index() action would simply redirect to /System/Auth/SignIn.
is there any Reverse Proxy Solution is the architecture which host your application ?

System.Web.HttpException: The file '/StudentPortal3G/Home.mvc.aspx' does not exist

Getting this error, everytime my home/INdex loads in my MVC3 app on Server 2008.
System.Web.HttpException: The file '/StudentPortal3G/Home.mvc.aspx' does not exist.
Tried all of this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"Default2", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults );
);
routes.MapRoute(
"Default3", // Route name
"{controller}.mvc.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults );
);
Views\Home\Index.aspx exists.
IIS7 is not supposed to need the .* handler.
Do I need to set the aspx handler to not check existance of file? But the file exists?
If this is the answer, how do I set it on iis7, I wasn't able to find that to try it.
Isn't there a way to do it in the handlers section of the web.config?
Again I found a few hint's but I'm not quite getting it.
Thanks,
Cal-
Did you add appropriate Views? In this case, you should have Views\StudentPortal3G\ (assuming that StudentPortal3G is a Controller) directory with Home.aspx inside and it maps to /StudentPortal3G/Home
Why are you trying to load Home.mvc.aspx at all is beyond me. I'd suggest you fire up RouteDebug to see which rules you are missing...

Resources