Configure asp.net mvc hocalhost/Products.aspx to hocalhost/Products - asp.net-mvc-3

How to configure asp.net mvc routing to redirect permanently 301
hocalhost/Products.aspx and hocalhost/Search.aspx
to
hocalhost/Products and hocalhost/Search
i.e. to remove .aspx extension from the path?

Something along these lines should do the trick. Map the following route:
routes.MapRoute("Redirect route", "{file}.aspx",
new { controller = "home", action = "redirect" });
And define a Redirect action in your controller:
public ActionResult Redirect()
{
// use Request.RawUrl, for instance to parse out what was invoked
// this regex will extract anything between a "/" and a ".aspx"
var regex = new Regex(#"(?<=/).+(?=\.aspx)", RegexOptions.Compiled);
var action = regex.Match(Request.RawUrl);
return RedirectToActionPermanent(action.Value);
}
You could redirect both aspx pages to the same redirect route and detect which file has actually been invoked by parsing HttpContext.Request.RawUrl (there might be a better way for this last point though).
UPDATE
There is indeed a simpler way, as found out by #alex himself. In order to get the file in the original request, just do:
string file = RouteData.Values["file"].ToString();

Related

How to redirect to view from shared folder

HttpContext.Response.Redirect("~/Shared/views/Error.cshtml", true);
This is not working for me
And how to exclude the certain controllers and actions
As you can see in documentation, method which you are trying to use require to arguments
public void Redirect(string url, bool endResponse)
and first argument is an url of page where user should be redirected, while you are passing view file path. In asp. mvc path to *cshtml file is not equal to url.
I suggest you to use RedirectToRoute method instead
RedirectToRoute(new RouteValueDictionary
{
controller = "Error",
action = "Index"
})
where your desired view is returned by ErrorController.Index() action.

Codeigniter - url segment replace or redirect

I have a base controller (base) which all other controllers extend from.
Anything placed here will override other controllers, the redirects will be here.
URLs example:
http://domain.com/controllerone/function
http://domain.com/controllertwo/function
http://domain.com/controllerthree/function
Using the code below. will give me the controller name
$this->uri->segment(1);
Each of the above controllers need to be redirected to separate URLs, but the funcation part should not change:
http://domain.com/newcontrollerone/function
http://domain.com/newcontrollertwo/function
http://domain.com/newcontrollerthree/function
In my base controller i want the following logic:
$controller_name = $this->uri->segment(1);
if($controller_name === 'controllerone'){
// replace the controller name with new one and redirect, how ?
}else if($controller_name === 'controllertwo'){
// replace the controller name with new one and redirect, how ?
}else{
// continue as normal
}
i was thinking i should use redirect() function and str_replace(), but dont know how efficient these would be. Ideally i do not want to use the Routing class.
thanks.
try
header("Location:".base_url("newcontroller/".$this->uri->segment(2)));
Simple Solution using segment_array:
$segs = $this->uri->segment_array();
if($segs[1] === 'controllerone'){
$segs[1] = "newcontroller";
redirect($segs);
}else if($segs[1] === 'controllertwo'){
$segs[1] = "newcontroller2";
redirect($segs);
}else{
// continue as normal
}
CodeIgniter's URI Routing, should be able to help in this case. However, if you have a good reason not to use it, then this solution may help.
The potential redirects are in an array, where the key is the controller name being looked for in the URL and the value is the name of the controller to redirect to. This may not be the most efficient but I think it should be easier to manage and read than a potentially very long if-then-else statement.
//Get the controller name from the URL
$controller_name = $this->uri->segment(1);
//Alternative: $controller_name = $this->router->fetch_class();
//List of redirects
$redirects = array(
"controllerone" => "newcontrollerone",
"controllertwo" => "newcontrollertwo",
//...add more redirects here
);
//If a redirect exists for the controller
if (array_key_exists($controller_name, $redirects))
{
//Controller to redirect to
$redirect_controller = $redirects[$controller_name];
//Create string to pass to redirect
$redirect_segments = '/'
. $redirect_controller
. substr($this->uri->uri_string(), strlen($controller_name)); //Function, parameters etc. to append (removes the original controller name)
redirect($redirect_segments, 'refresh');
}
else
{
//Do what you want...
}

MVC3 MapRoute to convert aspx query params into the route

I'm working on a project to rewrite an aspx site as MVC3. I want to make the old URLs work on the new site. I have named my controllers and actions such that the URLs actually contain enough info in the query string to route correctly but I'm having trouble getting the routing to work since it doesn't like the ? in the URL.
Basically I have old URLs like this:
www.example.com/Something/SomethingElse/MyPage.aspx?Section=DetailSection&TaskId=abcdef
I tried to create a route using:
routes.MapRoute(
"OldSite",
"Something/SomethingElse/MyPage.aspx?Section={action}Section&Id={id}",
new { controller = "Task", action = "Index", id = UrlParameter.Optional }
);
I want it to route to the correct new URL which is:
www.example.com/Task/Detail/abcdef
I know that all traffic to the MyPage.aspx page should go to my new Task controller and the beginning of the Section parameter always matches one of a few corresponding actions on that controller.
Unfortunately I have found that I get an error that a route can't contain a question marks. How should I handle this? Would it be better to use URL rewriting? Because this is a private site I'm not concerned with returning permanent redirects or anything - no search engine will have links to the site anyway. I just want to make sure that customers that have a URL in an old email will get to the right page in the new site.
In this one case I think the simplest way would be to have your old page mapped to a route:
routes.MapRoute(
"MyPage",
"Something/SomethingElse/MyPage.aspx",
new { controller = "Task", action = "MyPageHandler" }
);
And have this route mapped to an action method in TaskController:
public ActionResult MyPageHandler(string section, string taskId)
{
if (section.Contains("Detail"))
{
// execute section
}
}
This way you're treating your old site's query string for what it is: a query string. Passing those parameters straight into an action method is the most MVC-y way to interpret your old site.

Submit button which RedirectToAction to previusly page.

I have one method which I use in some place. Now I make RedirectToActio.... and back me to the concrete page. Is possible to make, it back to previusly page?
You could use the Referer HTTP header but it's not very reliable. A better way is to pass the url you want to redirect to the controller action (it's the way the POST LogOn method on the AccountController is implemented when you create a new ASP.NET MVC 3 application using the built in wizard. Take a look at it):
public ActionResult Foo(string returnUrl)
{
...
return Redirect(returnUrl);
}
Then when you call this action you pass the url of the current page. For example you could generate the following anchor:
#Html.ActionLink(
"do some processing and redirect back here",
"foo",
new { returnurl = Request.Url.AbsoluteUri }
)

How to accept email parameter in ASP.Net MVC 3

I'm using ASP.Net MVC 3 and am trying to pass an email address as a parameter in a URL like this:
www.myapp.co.uk/customers/changedetails/john#doe.com
The parameter value is null when passed in. If I use parameters then it works;
www.myapp.co.uk/customers/changedetails/?email=john#doe.com
My controller looks like this:
public class CustomerController {
[HttpGet]
public ViewResult ChangeDetails(string email)
{
var model = GetModel(email);
return View(model);
}
}
My register routes looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
What am I missing to be able to use the email as the {id} parameter (www.myapp.co.uk/customers/changedetails/john#doe.com)?:
Don't have e-mail as last route param. Or if you do, add a trailing slash.
/my/route/ee#mail.com -> fail
/my/route/ee#mail.com/ -> success
/my/ee#mail.com/route -> success
Reasoning behind this is quite complicated but here's a good article about these things http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx
What I am sure of is, that many times if you have e-mail as last without trailing slash, the request won't even reach the asp.net pipeline. It looks like a file request. That being said, It's *.com extension looks indeed very dangerous. Having an # in the file name certainly does not decrease it's suspiciousness.
You might get it working. You might need to loosen the security in order to do so but it almost certainly will break at some point.
So, the best option is to keep it as query string parameter. Second best option to trail it with a slash.
You need to add another route:
routes.MapRoute(
"ChangeEmail",
"customers/changedetails/{email}",
new { controller = "Customers", action = "ChangeDetails", email = UrlParameter.Optional }
);
The URL parameter name needs to match the action method parameter name.
You can try add the following code into your web.config.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
This is because the IIS Express think ".com" as an extension and looks for related module to handle it. However, there isn't related module, so it call the static module to handle it. Then it will search for a static content file path "/customers/changedetails/john#doe.com", then it report the 404 not found error.
Add above code in your web.config will make your request contain email handled by MVC module instead of StaticFile Module.

Resources