No trailing slash in hostname, HttpResponse.RemoveOutputCacheItem doesn't work - asp.net-mvc

I'm in a bit of a pickle here.
I have an action for which the output is fairly static, until another action is used to update the datasource for the first action. I use HttpResponse.RemoveOutputCacheItem to remove that action's cached output so that it is refreshed next time the user loads it.
Basically I have an action like this:
[OutputCache(Duration=86400, Location=OutputCacheLocation.Server)]
public ActionResult Index()
{
return ...
}
on my HomeController, and another action on another controller that updates the information used in the former:
public ActionResult SaveMenu(int id, Menu menu)
{
...
HttpResponse.RemoveOutputCacheItem(Url.Action("Index", "Home"));
...
}
The crazy thing is that this works, as long as you're either loading the URLs http://site/ or http://site/Home/Index. When you use the URL http://site it never refreshes.
Why is that?

It has to do with the way the OutputCacheAttribute works, specifically on its dependency on RouteData not being null. The relevant part is:
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (!filterContext.IsChildAction)
{
new OutputCachedPage(this._cacheSettings).ProcessRequest(HttpContext.Current);
}
}
The ResultExecutingContext filterContext derives from ControllerContext. This is the source for ControllerContext.IsChildAction:
public virtual bool IsChildAction
{
get
{
RouteData routeData = this.RouteData;
if (routeData == null)
{
return false;
}
return routeData.DataTokens.ContainsKey("ParentActionViewContext");
}
}
So, why is this relevant to your question?
Because when you omit the "/" then your Route does not match anything. The default route is "/". An article that explains this more in depth is here: http://www.58bits.com/blog/2008/09/29/ASPNet-MVC-And-Routing-Defaultaspx.aspx . It was written to explain why the Default.aspx file was necessary in ASP.NET MVC 1 projects, but the reason is rooted in the same place.
So, basically, the RouteData is null, so the OutputCacheAttribute can't work. You can solve your problem by doing what Michael Jasper suggested and leveraging URL Rewriting.

IIS has a very usefull module called URL Rewrite. One of the options is to remove or append a trailing slash to all/specific urls. If it is simply the trailing slash that is the problem, this should work.

I've seen a similar behavior in the way SharePoint behaves. SharePoint became confused with http://site; it was unable to determine if the URL was to a File or a SharePoint Site. There's probably something similar going on here.
You've probably resolved the problem by appending the URL with a trailing slash; but, just in case you haven't:
url = string.Format( "{0}/", url.TrimEnd( '/' ) );

Related

RequestContext - RouteData does not contain action

So i've created my own ControllerFactory and i'm overloading GetControllerSessionBehavior in order to extend the MVC behavior.
To do my custom work i have to use reflection on the called action. However i've stumbled upon a weird issue - i can't retrieve the action by accessing RequestContext.RouteData
While setting up a reproduction sample for this i was not able to reproduce the error.
Is anyone aware of possible reasons for this or knows how to retrieve the action by calling a method with the request context other than this?
public class CustomControllerFactory : DefaultControllerFactory
{
protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)
{
if (!requestContext.RouteData.Values.ContainsKey("action"))
return base.GetControllerSessionBehavior(requestContext, controllerType);
var controllerAction = requestContext.RouteData.Values["action"];
var action = controllerAction.ToString();
var actionMethod = controllerType.GetMember(action, MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public).FirstOrDefault();
if(actionMethod == null)
return base.GetControllerSessionBehavior(requestContext, controllerType);
var cattr = actionMethod.GetCustomAttribute<SessionStateActionAttribute>();
if (cattr != null)
return cattr.Behavior;
return base.GetControllerSessionBehavior(requestContext, controllerType);
}
}
Action which i can call just fine but can't access the action name of within my controller factory:
[Route("Open/{createModel:bool?}/{tlpId:int}/{siteId:int?}")]
public ActionResult Open(int tlpId, int? siteId, bool? createModel = true)
{
}
Any ideas welcome.
Update:
The problem seems to be related to attribute routing. While it's working fine in repro it doesn't work in production for me.
Found this along the way - Once this is answered i'll have my proper solution too i guess.
Update 2:
Interesting. Reproduction MVC Version 5.0.0.0, Production 5.2.2. Possible introduction of bug?
I can confirm that there was a breaking change to attribute routing between 5.0.0 and 5.1.1. I reported the issue here. However, for my use case Microsoft was able to provide an acceptable workaround.
On the other hand, the problem you are bumping into looks like another culprit. For attribute routing, the route values are stored in a nested route key named MS_DirectRouteMatches. I am not sure exactly which version that changed in, but I know it happened v5+.
So, to fix your issue, you will need to check for the existence of a nested RouteData collection, and use instead of the normal RouteData in the case it exists.
var routeData = requestContext.RouteData;
if (routeData.Values.ContainsKey("MS_DirectRouteMatches"))
{
routeData = ((IEnumerable<RouteData>)routeData.Values["MS_DirectRouteMatches"]).First();
}
var controllerAction = routeData.Values["action"];
var action = controllerAction.ToString();
BTW - In the linked question you provided, the asker assumed that there is a possibility where a request can match more than one route. But that is not possible - a request will match 0 or 1 route, but never more than one.

How to validate a path in ASP.NET MVC 2?

I have a custom attribute that checks conditions and redirects the user to parts of the application as is necessary per business requirements. The code below is typical:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// ...
if (condition)
{
RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
redirectTargetDictionary.Add("action", "MyActionName");
redirectTargetDictionary.Add("controller", "MyControllerName");
filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
}
// ...
base.OnActionExecuting(filterContext);
}
I was just asked to allow the user to choose a default page that they arrive at upon logging in. Upon adding this feature, I noticed that the user can get some unusual behavior if there is no action/controller corresponding to the user's default page (i.e. if the application were modified). I'm currently using something like the code below but I'm thinking about going to explicit actions/controllers.
else if (condition)
{
var path = "~/MyControllerName/MyActionName";
filterContext.Result = new RedirectResult(path);
}
How do I check the validity of the result before I assign it to filterContext.Result? I want to be sure it corresponds to a working part of my application before I redirect - otherwise I won't assign it to filterContext.Result.
I don't have a finished answer, but a start would be to go to the RouteTable, get the collection, call GetRouteData with a custom implementation of HttpContextBase to get the RouteData. When done, if not null, check if the Handler is an MvcRouteHandler.
When you've got so far, check out this answer :)

In Asp.Net MVC 2 is there a better way to return 401 status codes without getting an auth redirect

I have a portion of my site that has a lightweight xml/json REST API. Most of my site is behind forms auth but only some of my API actions require authentication.
I have a custom AuthorizeAttribute for my API that I use to check for certain permissions and when it fails it results in a 401. All is good, except since I'm using forms auth, Asp.net conveniently converts that into a 302 redirect to my login page.
I've seen some previous questions that seem a bit hackish to either return a 403 instead or to put some logic in the global.asax protected void Application_EndRequest()
that will essentially convert 302 to 401 where it meets whatever criteria.
Previous Question
Previous Question 2
What I'm doing now is sort of like one of the questions, but instead of checking the Application_EndRequest() for a 302 I make my authorize attribute return 666 which indicates to me that I need to set this to a 401.
Here is my code:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == MyAuthAttribute.AUTHORIZATION_FAILED_STATUS)
{
//check for 666 - status code of hidden 401
Context.Response.StatusCode = 401;
}
}
Even though this works, my question is there something in Asp.net MVC 2 that would prevent me from having to do this? Or, in general is there a better way? I would think this would come up a lot for anyone doing REST api's or just people that do ajax requests in their controllers. The last thing you want is to do a request and get the content of a login page instead of json.
How about decorating your controller/actions with a custom filter:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class RequiresAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var user = filterContext.HttpContext.User;
if (!user.Identity.IsAuthenticated)
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
}
}
}
and in your controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[RequiresAuthentication]
public ActionResult AuthenticatedIndex()
{
return View();
}
}
Another way of doing this is to implement a custom ActionResult. In my case, I wanted one anyway, since I wanted a simple way of sending data with custom headers and response codes (for a REST API.) I found the idea of doing a DelegatingActionResult and simply added to it a call to Response.End(). Here's the result:
public class DelegatingActionResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
Command(context);
// prevent ASP.Net from hijacking our headers
context.HttpContext.Response.End();
}
private readonly Action<ControllerContext> Command;
public DelegatingActionResult(Action<ControllerContext> command)
{
if (command == null)
throw new ArgumentNullException("command");
Command = command;
}
}
The simplest and cleanest solution I've found for this is to register a callback with the jQuery.ajaxSuccess() event and check for the "X-AspNetMvc-Version" response header.
Every jQuery Ajax request in my app is handled by Mvc so if the header is missing I know my request has been redirected to the login page, and I simply reload the page for a top-level redirect:
$(document).ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions) {
// if request returns non MVC page reload because this means the user
// session has expired
var mvcHeaderName = "X-AspNetMvc-Version";
var mvcHeaderValue = XMLHttpRequest.getResponseHeader(mvcHeaderName);
if (!mvcHeaderValue) {
location.reload();
}
});
The page reload may cause some Javascript errors (depending on what you're doing with the Ajax response) but in most cases where debugging is off the user will never see these.
If you don't want to use the built-in header I'm sure you could easily add a custom one and follow the same pattern.
TurnOffTheRedirectionAtIIS
From MSDN, This article explains how to avoid the redirection of 401 responses : ).
Citing:
Using the IIS Manager, right-click the
WinLogin.aspx file, click Properties,
and then go to the Custom Errors tab
to Edit the various 401 errors and
assign a custom redirection.
Unfortunately, this redirection must
be a static fileā€”it will not process
an ASP.NET page. My solution is to
redirect to a static Redirect401.htm
file, with the full physical path,
which contains javascript, or a
meta-tag, to redirect to the real
ASP.NET logon form, named
WebLogin.aspx. Note that you lose the
original ReturnUrl in these
redirections, since the IIS error
redirection required a static html
file with nothing dynamic, so you will
have to handle this later.
Hope it helps you.
I'm still using the end request technique, so I thought I would make that the answer, but really
either of the options listed here are generally what I would say are the best answers so far.
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == MyAuthAttribute.AUTHORIZATION_FAILED_STATUS)
{
//check for 666 - status code of hidden 401
Context.Response.StatusCode = 401;
}
}

ASP.Net MVC routing legacy URLs passing querystring Ids to controller actions

We're currently running on IIS6, but hoping to move to IIS 7 soon.
We're moving an existing web forms site over to ASP.Net MVC. We have quite a few legacy pages which we need to redirect to the new controllers. I came across this article which looked interesting:
http://blog.eworldui.net/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx
So I guess I could either write my own route handler, or do my redirect in the controller. The latter smells slightly.
However, I'm not quite sure how to handle the query string values from the legacy urls which ideally I need to pass to my controller's Show() method. For example:
Legacy URL:
/Artists/ViewArtist.aspx?Id=4589
I want this to map to:
ArtistsController Show action
Actually my Show action takes the artist name, so I do want the user to be redirected from the Legacy URL to /artists/Madonna
Thanks!
depending on the article you mentioned, these are the steps to accomplish this:
1-Your LegacyHandler must extract the routes values from the query string(in this case it is the artist's id)
here is the code to do that:
public class LegacyHandler:MvcHandler
{
private RequestContext requestContext;
public LegacyHandler(RequestContext requestContext) : base(requestContext)
{
this.requestContext = requestContext;
}
protected override void ProcessRequest(HttpContextBase httpContext)
{
string redirectActionName = ((LegacyRoute) RequestContext.RouteData.Route).RedirectActionName;
var queryString = requestContext.HttpContext.Request.QueryString;
foreach (var key in queryString.AllKeys)
{
requestContext.RouteData.Values.Add(key, queryString[key]);
}
VirtualPathData path = RouteTable.Routes.GetVirtualPath(requestContext, redirectActionName,
requestContext.RouteData.Values);
httpContext.Response.Status = "301 Moved Permanently";
httpContext.Response.AppendHeader("Location", path.VirtualPath);
}
}
2- you have to add these two routes to the RouteTable where you have an ArtistController with ViewArtist action that accept an id parameter of int type
routes.Add("Legacy", new LegacyRoute("Artists/ViewArtist.aspx", "Artist", new LegacyRouteHandler()));
routes.MapRoute("Artist", "Artist/ViewArtist/{id}", new
{
controller = "Artist",
action = "ViewArtist",
});
Now you can navigate to a url like : /Artists/ViewArtist.aspx?id=123
and you will be redirected to : /Artist/ViewArtist/123
I was struggling a bit with this until I got my head around it. It was a lot easier to do this in a Controller like Perhentian did then directly in the route config, at least in my situation since our new URLs don't have id in them. The reason is that in the Controller I had access to all my repositories and domain objects. To help others this is what I did:
routes.MapRoute(null,
"product_list.aspx", // Matches legacy product_list.aspx
new { controller = "Products", action = "Legacy" }
);
public ActionResult Legacy(int catid)
{
MenuItem menuItem = menu.GetMenuItem(catid);
return RedirectPermanent(menuItem.Path);
}
menu is an object where I've stored information related to menu entries, like the Path which is the URL for the menu entry.
This redirects from for instance
/product_list.aspx?catid=50
to
/pc-tillbehor/kylning-flaktar/flaktar/170-mm
Note that RedirectPermanent is MVC3+. If you're using an older version you need to create the 301 manually.

How to config Asp.net Mvc for redirecting every request to configuration page?

For Asp.net Mvc project, I need to redirect every request to configuration page when user(should be admin of this website) visit this website at the first time. This operation like default login page(every request will be redirect to default login page if access denied).
After user config the configuration file, Route table will be mapped to normal controllers.
Ps. This page should helps Admin for detect error configuration and easy to deploy.
Update #1
I try to use ASP.NET MVC WebFormRouting Demo on Codeplex. But I can't redirect when user visit some existing page like "~/AccessDenied.aspx" or "~/web.config".
routes.MapWebFormRoute("RedirectToConfig", "{*anything}", "~/App_Config");
Thanks,
From your description, this appears to be an authorization concern, so I would recommend a custom Authorize attribute class (inherit from AuthorizeAttribute).
From here you can override the OnAuthorization method where you can check if the user has completed your required configuration steps and set the filterContext.Result accordingly. A basic implementation would look something like this (this assumes you have a valid /Account/Configure route):
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
var user = ; // get your user object
if(user.IsConfigured == false) // example
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{
"ConfigureUserRoute",
filterContext.RouteData.Values["ConfigureUserRoute"]
},
{"controller", "Account"},
{"action", "Configure"}
});
return;
}
}
}
You can find other examples of how to create a custom AuthorizeAttribute class here on StackOverflow.
2 ideas:
Use a catch-all rule on top of your routing table and put a constraint on it that checks for the config status
Put the code for this check in Application_BeginRequest in GlobalAsax
Details for the catch-all idea:
Create a rule with url "{*path}" and put it first in your list
Create a constraint to activate this rule only in case the configuration is not done yet
Create a simple controller e.g. ConfigController with a single action that does nothing but a RedirectToUrl("config.aspx")
But the solution in Application_BeginRequest would be simpler, since the whole code to handle this in one place
Now, I can apply technique from my another question to solve this problem. By keep some value in static instance when application is starting. Please look at the following code.
partial ConfigBootstapper.cs
public class ConfigBootstapper
{
public static EnableRedirectToConfigManager = false;
}
partial ConfigModule.cs
void HttpApplication_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (ConfigBootstapper.EnableRedirectToConfigManager)
{
app.Response.Redirect("~/App_Config");
}
}
partial Global.asax
protected void Application_Start()
{
[logic for setting ConfigBootstapper.EnableRedirectToConfigManager value]
}
PS. Don't forget to checking some condition that cause infinite-loop before redirect.

Resources