MVC 4 Filter result - redirect or view? - c#

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.

Related

ASP.NET MVC route to return user to origin from partial view

I'm using ASP.NET MVC in Visual Studio 2015. The app has the following structure:
MyApp
Controllers
Controller1
Actions
Create
Delete
Details
Edit
IndexPartial
Controller2
Actions
Edit
Controller3
Actions
Edit
Views
Controller1
Create
Delete
Details
Edit
IndexPartial
Controller2
Edit
Controller3
Edit
The app displays Controller1/IndexPartial view on the Controller2/Edit view and on Controller3/Edit. This partial view displays rows of data, each with Edit, Details, Delete buttons which take the user to the Controller1 views for those actions.
When the user is done with the Controller1 action, they need to return to Controller2/Edit or Controller3/Edit via the Back to List button or when the Save/Delete buttons are clicked. But how do we determine where the user originated? Did the user come from the Edit of Controller2 or Controller3?
We've thought of using a session variable. Can RouteConfig.cs be used to track the user's path and help determine where s/he should return? How do we do this via routes in MVC?
Thank you for your help.
Update: This is all done via the server; no JavaScript (Angular, etc.).
The routing engine has nothing to do with what you need. You need to track user navigation and a good way to do this is using ActionFilters.
You can create a custom ActionFilter that checks the UrlReferrer on its OnActionExecuted and decides how to redirect the request to the appropriate Controller/Action.
[Example]
ActionFilter
public class RedirectAfterActionFilter : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Your decision logic
if (filterContext.HttpContext.Request.UrlReferrer.AbsolutePath == "something usefull")
{
filterContext.Result = new RedirectToRouteResult("Your Route Name", routeValues: null); // redirect to Home
}
base.OnActionExecuted(filterContext);
}
}
ActionFilter usage
[RedirectAfterActionFilter]
public ActionResult DoSomethingAndGetRedirected()
{
// Save, Edit or Whatever
//...
return new EmptyResult(); // no need to return since the user will be redirected by the filter
}
Extra: Read How to redirect from a action filter if you dislike to use Route names to redirect.
There are two aspects to this:
The "Back to List" link
The "Save/Delete" actions
As far as the "Back to List" link, your controller should be giving the view all the information it needs to produce a viable GUI. Pass an identifier (or even the actual return URL) to the view in the ViewBag as a dynamic property and let the view render the link to the destination.
For the "Save/Delete" actions, it depends on how they are implemented.
If it's all JS with http requests then the same concept above applies.
If you are posting back to the server however, the controller will have to do the redirection with something like RedirectToAction().
How about storing the previous location in a ViewBag and then populate your button href with the ViewBag content...
Or
You can use Url Referrer, which fectches the previous url that linked to current page.
Of course the best method will depend on your implementantion, without seeing your code those two are the best option that I can think of.

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.

How to change url for MVC4 WebSite?

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

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
);

ASP.NET MVC: Filtering/Varying by HTTP Status Code in OutputCache Attribute

In the ASP.NET MVC site that I'm writing, I'm building a generic Error Action that is routed to by an HttpModule, following this tutorial. In this Action, I will return a View corresponding to the status code that is applied to the response inside the HttpModule (after doing this, the module transfers the request over to the Action in question).
That's all good, except that I want to implement caching. I don't want to use the OutputCache attribute without filtering/varying, because that would mean that the page would be cached once. I want the page to be cached once for every possible status code.
Is it possible to somehow filter/vary with OutputCacheAttribute's properties, so that each Response.StatusCode is cached separately?
How are you currently handling the routing to your error action, e.g. you could have:
/Errors/404
/Errors/500
All pointing to the exact same action, and the caching will be handled for you because they are independent urls and you apply the OutputCache attribute a single time to the generic error action:
[OutputCache]
public ActionResult DisplayError(int errorCode) {
return View(errorCode.ToString());
}
Would that work?

Categories

Resources