How to change url for MVC4 WebSite? - c#

I need to change the URL on my address bar.
I looked for URL Rewrite but as far as I've seen it works for a request like this:
url.com/mypage.aspx?xp=asd&yp=okasd
and transforms that into:
url.com/mypage/asd/okasd
http://www.iis.net/downloads/microsoft/url-rewrite
That's not my scope. I already have MVC Routes working with url.com/mypage. The problem is that when I type that URL I am redirected (that's the behavior I want) to url.com/otherpage/actionX?param=value. The problem is that I still want the address bar to show url.com/mypage. Will URL Rewrite work for that?
I am asking because I don't know if it will work since it's an internal redirect (RedirectToAction) instead of a 'regular' access.
In case someone wonders why I can't make a route for that, as explained in my question I alread have one rule for that url.com/mypage that redirects to a 'router' which decides what action to call.
I've seen some questions, but I don't think they cover my specific problem:
MVC3 change the url
C# - How to Rewrite a URL in MVC3
UPDATE
This is my route:
routes.MapRoute(
"Profile", // Route name
"{urlParam}", // URL with parameters
new { controller = "Profile", action = "Router" } // Parameter defaults
);
Inside Router action I redirect to the correct action according to some validation done on urlParam. I need this behavior since each action returns a different View.
Updated my tags since I am now using MVC4
Thanks.

I once had to run a php site on a windows box. On the linux box it originally ran, it had a rewrite defined to make site process all request in only one php file (index.php).
I've installed and configured URL Rewrite with following parameters
Name : all to index.php
Match URL ------------------------------
Requested URL : Matches the Pattern
Using : Regular Expressions
Pattern : (.*)
Ignore Case : Checked
Conditions -----------------------------
Logical Grouping : Match All
Input : {REQUEST_FILENAME}
Type : Is Not a File
Action ---------------------------------
Action Type : Rewrite
Action Properties:
Rewrite Url : /index.php?$1
Append Query String : Checked
Log Rewritten URL : Checked
this makes all requests to site (except files like css and js files) to be processed by index.php
so url.com/user/1 is processed on server side as url.com/index.php?/user/1
since it works on server side client url stays same.
using this as you base you can build a rewrite (not a redirect).

Server.Transfer is exactly what you need, but that is not available on MVC.
On the MVC world you can use the TransferResult class defined in this thread.
With that... you add code to your ROUTE action that process the urlParam as always and instead of "redirecting" (RedirectToAction) the user to a new URL, you just "transfer" him/her to a new action method without changing the URL.
But there it a catch (I think, I have not tested it)... if that new page postbacks something... it will NOT use your router's action URL (url.com/mypage), but the real ACTION (url.com/otherpage)
Hope it helps.

In my opinion,you can try following things:
Return EmptyResult or RedirectResult from your Action method.
Also,you need to setup and construct outbound route for URL that you required.
Secondly, if these didn't work,the crude way to handle this situation is with Div tag and replacing the contents of Div with whatever HTML emitted by Action method. I am assuming here that in your problem context, you can call up jquery ajax call.
Hope this Helps.

The problem you have is that you redirect the user ( using 302 http code) to a new location, so browser ,reloads the page. you need to modify the routes to point directly to your controller. The route registration should be routes.MapRoute("specific", "my page", new { controller = "otherpage", action="actions", param="value"}).
This route should be registered first

Related

Update URL from action filter ASP.NET MVC

Hellp all,
Generally speaking I want to "update" URL from action filter in OnActionExecuting method. I registered action filter to be global and that method will be executed before every action is executed.
In OnActionExecuting method I am processing some things and I want to update URL with accountName after that.
I have configured routes which can accept four segments route patterns - something like these: {accountName}/{controller}/{action}, {controller}/{action}...
Basically if I receive request which doesn't contain {accountName} segment or if is that segment empty I would like to update URL with new accountName and be able to see updated URL when request is ended.
I am trying to do that like in following:
filterContext.RouteData.Values["accountName"] = accountName;
filterContext.Result = new RedirectToRouteResult("AccountRoute", filterContext.RouteData.Values);
I added new route data value to filterContext and after I am trying to redirect to specific route with route data values.
That approach doesn't properly because I am encountered with "TO MANY REQUESTS" and it broke my app.
Any idea how I can update URL and avoid to many requests?
Thanks

Routing Issue want to display domain name even index.aspx is called

routes.MapPageRoute("Main", "", "~/index.aspx");
thats the route I mapped on index page..
when I call the url with index.aspx it displays like
www.abc.com/index.aspx
but I want it to show
www.abc.com
even when index.aspx is called
Regarding my comment, URL Rewrite is also available in IIS and Asp.net. So you can potentially use it.
Another solution would be to redirect to your route. The route alone doesn't change the URL, it just allows you to access the resource via the defined route.
You can redirect to the route though, which will rewrite the URL on the client
For example like this:
if (Request.Path != "/")
{
Context.Response.RedirectToRoute("Main");
}
This is very simplified and might not work in all scenarios, so please be very careful.

MVC 4 Filter result - redirect or view?

I am building MVC 4 application.
The authorization and exception handling is done using Filters.
In filter, I can either redirect user to my error page using RedirectToRouteResult
or return view of my error page using ViewResult.
Which variant is better in practice and why?
1.Return View doesn't make a new requests, it just renders the view without changing URLs in the browser's address bar.
2.Return RedirectToAction makes a new requests and URL in the browser's address bar is updated with the generated URL by MVC.
3.Return Redirect also makes a new requests and URL in the browser's address bar is updated, but you have to specify the full URL to redirect
4.Between RedirectToAction and Redirect, best practice is to use RedirectToAction for anything dealing with your application actions/controllers. If you use Redirect and provide the URL, you'll need to modify those URLs manually when you change the route table.
5.RedirectToRoute redirects to a specific route defined in the Route table.
If you want to move on error page with static data with limited messages then use ViewResult else use RedirectToRouteResult in this you can use as you want.
It depends on whether there is any logic in an error action that populates a view model (e.g.setting the http status code) or you only have a static view. Of course you could move this logic to the filter, but this would prevent you from being able to redirect from another action that doesn't use the same filter.

Stackoverflow style URL (customising outgoing URL)

If I navigate to the following stackoverflow URL http://stackoverflow.com/questions/15532493 it is automatically appended with the title of the question like so:
http://stackoverflow.com/questions/15532493/mvc-custom-route-gives-404
That is, I can type the URL into my browser without the question title and it is appended automatically.
How would I go about achieving the same result in my application? (Note: I am aware that the question title doesn't affect the page that is rendered).
I have a controller called Users with an action method called Details. I have the following route defined:
routes.MapRoute("UserRoute",
"Users/{*domain}",
new { controller = "User", action = "Details" },
new { action = "^Details$" });
As this is an intranet application the user is authenticated against their Windows account. I want to append the domain and user name to the URL.
If I generate the URL in the view like so:
#Html.ActionLink("Model.UserName", "Details", "User", new { domain = Model.Identity.Replace("\\", "/") })
I get a URL that look like this:
Domain/Users/ACME/jsmith
However, if the user navigates to the URL Domain/Users/ by using the browsers navigation bar it matches the route and the user is taken to the user details page. I would like to append the ACME/jsmith/ onto the URL in this case.
The research I have done so far indicates I might have to implement a custom route object by deriving from RouteBase and implementing the GetRouteData and GetVirtualPath methods but I do not know where to start with this (the msdn documentaiton is very thin).
So what I would like to know is:
Is there a way of achieving this without implementing a custom route?
If not, does anyone know of any good resources to get me started implementing a custom route?
If a custom route implementation is required, how does it get at the information which presumably has to be loaded from the database? Is it OK to have a service make database calls in a route (which seems wrong to me) or can the information be passed to the route by the MVC framework?
It's actually pretty simple. Since the title is just there for SEO reasons you do not need to get to the actual question, so the Question controller (in SO case) will load the correct question based on the id (in the URL) and redirect the user with a 301 status code.
You can see this behavior with any web inspector
You could do it client-side with Javascript:
history.pushState({}, /* Title Here */, /* URL Here */ );
Only downside is not all browsers support it.

i have a project where i need to make special routing how i can make my own rule?

in my own site i need a thing that page are known by #topic.
it's need to look like
mywebsite.com#google [are this possible i need to pass google as parameter]
OR
mywebsite.com/#google [if first can not be done then how i can use it]
how i can apply this thing in my website. the thing i need to done that
if anyone open the site mywebsite.com#google that the content genrate dynamically through [passing google as parameter]
can anyone show how i can make routing for this
You can't use routing for this. The value that follows the # sign in an URL is NEVER sent to the server by the client browser. So for example if you request http://example.com/someaction#google the server can never fetch the value google simply because the browser never sends it. The only way is to use javascript (window.location.hash) and maybe send an AJAX request to the server by rewriting the url : http://example.com/someaction?param=google
You have the route table at Global.asax. Add this on the method RegisterRoutes. I am not so sure if it will work as I didn't test but that can give you a good start.
routes.MapRoute(
"RouteWithSharp",
"#{page}",
new { controller = "Home", action = "Index", page = "" } // Parameter defaults
);

Categories

Resources