Is there a way to rename the RequestVerificationToken cookie name? - asp.net-mvc

Using ASP.net MVC v2.0, Any way to change the name of the __RequestVerificationToken cookie? In an effort to conceal our underlying technology stack, I’d like to rename the cookie to something that can’t be traced back to ASP.Net MVC.
More info on this at Steve Sanderson's blog.

ASP.NET MVC 3 and 4 let you change the cookie name by setting the static AntiForgeryConfig.CookieName property.
(Msdn reference here)
I know that the question asks specifically about ASP.NET MVC 2, but this question still returns high up the search engine rankings for appropriate queries such as "ASP.NET MVC AntiForgeryToken cookie name". I thought I'd add the information here to save others from decompiling the ASP.NET MVC 3+ source code like I did.

Looking at the MVC 2 source code I dont think it's possible to change the cookie name. The AntiForgeryData class starts:
private const string AntiForgeryTokenFieldName = "__RequestVerificationToken";
and to get the cookie name it just calls:
string cookieName = AntiForgeryData.GetAntiForgeryTokenName(ViewContext.HttpContext.Request.ApplicationPath);
in the HtmlHelper class. It takes the application path and converts it to base 64 and appends it onto the end of __RequestVerificationToken which is what you see when you view the source.
If you really need to change the name I'd recommend downloading the MVC 2 source code from codeplex and look at creating your own html helper and anti forgery token using the source code as a reference. But in doing this you could always introduce your own bugs...

Related

How to pass information to Asp.Net MVC partial view?

In Asp.Net MVC, the Account controller's Login method, if successful, returns RedirectToLocal(returnUrl);
I want to add a string to return. I thought ViewBag or TempData would do, but the View finds those to be empty. So I guess those don't get passed to the View, even though that's their exact purpose, from what I read.
There's got to be an easy way...other than returning to Classic ASP.
It sounds like you want to declare (optional?) parameters on the route you're redirecting to.
For example, something like:
return RedirectToAction("Action", new { id = 99 });
Here are a few links that might help:
MVC RedirectToAction passing route parameters
Passing data from one controller to another in ASP.NET MVC
PS:
Please don't return to "Classic ASP.Net" (or "even-more-classic ASP 3.0" ;)). Get familiar with MVC, and look forward to ASP.Net Core (which is MVC from the ground up ;))

asp.net mvc 4 - Who calls _ViewStart.cshtml and what is the sequence of steps

I am new to MVC so please bear with me. I am trying to find out who calls Viewstart.cshtml and what is the sequence of steps involved there? is it called after the route table is accessed or before it?
The RazorViewEngine has an internal readonly field "ViewStartFileName" which specifies the name of the start view. _ViewStart.cshtml (or .vbhtml) is called each time a RazorView instance is rendered (specifically when the RenderView() method is being executed).
So the "who" would be the RazorViewEngine with its corresponding RazorView class (including their base classes). To get a quite good overview on the MVC request pipeline I recommend this pdf.
Check the image below... (What is the 'page lifecycle' of an ASP.NET MVC page, compared to ASP.NET WebForms?)

Sending a parameter to the controller in ASP MVC 2

I am writing an area for administering several subsites, almost all of the functionality will be the same across each site (add/edit/remove pages etc) and my repository on instantiation takes the SiteIdentity so all the data access methods are agnostic in relation to this. The problem I have at the moment is trying to make my action methods also agnostic.
The URL pattern I want to use is along the lines of:
"ExternalSite/{identity}/{controller}/{action}/{id}"
A naive approach is to have each action take the identity parameter, but this means having to pass this in to my repository on each action as well as include it in the ViewData for a couple of UI elements. I'd much rather have this something that happens once in the controller, such as in its constructor.
What is the best way to do this? Currently the best I can come up with is trying to find and cast identity from the RouteData dictionary but part of me feels like there should be a more elegant solution.
It sounds like you want to use OnActionExecuting or a Custom ModelBinder to do that logic each time you have a specific parameter name (also known as a RouteData dictionary key).
Creating a custom modelbinder in ASP.NET MVC
Creating an OnActionExecuting method in ASP.NET MVC, Doing Serverside tracking in ASP.NET MVC
You have access to your route values in Request.RequestContext.RouteData, so you can make base controller and public property SiteIdentity, in such case you can access it from all actions in all inherited controllers.

ASP.NET MVC "Convert to Web Application" option is missing in Visual Studio

I'm working with Visual Studio 2008 SP1 and ASP.NET MVC v1. When right clicking on a view I do not get the option "Convert to Web Application" that I would need to generate code behind .cs classes. I see that option for the actual project and folders, but not for views (aspx files). I've checked the ProjectTypeGuids to have the "right" (?) values:
{603c0e0b-db56-11dc-be95-000d561079b0};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
Any other suggestions as to what I could look for?
Thanks.
(I am aware of design implications of using code behind classes with MVC)
P.S. To do it manually all you have to do is:
Add a file with the same name as your view and the .cs (or .vb) extension, for example Index.aspx.cs. Make sure you modify your class to inherit from System.Web.Mvc.ViewPage or some other class that inherits from that.
Edit the aspx file and add to the #Page directive CodeBehind="Index.aspx.cs" and change Inherits to "MyNamespace.Views.Home.Index" (obviously you need to have the right code behind and namespace there).
Right click on the aspx file and choose Convert to Web Application. This will create the design file and also modify your .cs class and mark it as "partial".
"Convert to web application" is a project/file-level command. You can't use it on a single ASPX file.
Also, there is no alternative automated way (that I know of :-)) to add code-behind files to an ASPX file. You have to do it manually, by adding the relevant files yourself and then adding them to the .csproj.
There's no need to use 'code-behind' with ASP.NET MVC.
If you use a 'code-behind', you're not following the convention of ASP.NET MVC.
The question is, why do you want a code-behind? Answering that will help us to determine what you really need.
If you really want to do this, you can do it by mixing Webforms and ASP.NET MVC together. There are lots of resources on this, but here's just one.
The MVC development model does not need code behind.
Read a good Blog Post on this Here
If you're trying to reuse some controls, maybe a good approach is to create and render them inside a helper method and than call that method from the view.
What I'm thinking about would be something like this:
public static string HelperMethod(param_list)
{
var control = new ControlType();
//set up control properties according to param_list
//get the html as string - one way to do it would be like this
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter= new HtmlTextWriter(stringWriter);
control.RenderControl(htmlWriter);
string result= stringWriter.ToString();
}
And then call it from the view like this:
<%= HelperClass.HelperMethod(params) %>
I'm not sure if this approach will work, I don't know even if it makes sense. It's more of I hack than a proper solution. I haven't done anything like this before, it's just an idea, try to see if it helps you. You should also have in mind that ASP.NET controls usually use the ViewState for state management and that there is no such thing in ASP.NET MVC.

ASP.NET MVC Response Filter + OutputCache Attribute

I'm not sure if this is an ASP.NET MVC specific thing or ASP.NET in general but here's what's happening. I have an action filter that removes whitespace by the use of a response filter:
public class StripWhitespaceAttribute : ActionFilterAttribute
{
public StripWhitespaceAttribute ()
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
filterContext.HttpContext.Response.Filter = new WhitespaceFilter(filterContext.HttpContext.Response.Filter);
}
}
When used in conjunction with the OutputCache attribute, my calls to Response.WriteSubstitution for "donut hole caching" do not work. The first and second time the page loads the callback passed to WriteSubstitution get called, after that they are not called anymore until the output cache expires. I've noticed this with not just this particular filter but any filter used on Response.Filter... am I missing something?
I also forgot to mention I've tried this without the use of an MVC action filter attribute by attaching to the PostReleaseRequestState event in the global.asax and setting the Response.Filter value there... but still no luck.
This KB article may offer some insight into the root cause of this issue. While the filter 'breaks' caching in IIS6 it throws an error in IIS 7. This seems to be a design / test-time improvement at best.
UPDATE
Here's an official "answer" from MS Dev Support on this issue.
Question:
What is the alternative to response filtering in ASP.NET for modifying HTML rendered by another process when:
1. The other process cannot be modified
2. Post-cache substitution must be supported
Answer:
"Yes, you question is clear as blue sky and this is officially claimed to be not support. As Post-cache substitution would combine certain substitution chunks to the response bytes while response filtering expects to filter the raw bytes of the response(not modified). So the previously combined substitution chunks cannot be preserved anymore.
There is not an alternative from Microsoft so far."
AFAIK, the problem is that the action filters doesn't get executed if the request goes to the output cache. The AuthorizeAttribute works around this problem by calling some obscure Output Cache API. However, I don't think that is the best solution for what you're are trying to do.
You should be working with output cache, not around it. What you should be doing instead is making sure that the spaces are removed from the response before it gets stored in the output cache.
Update
It seems that attaching a filter, no matter what filter, disables the WriteSubstitution functionality as you suspect. I've tried following the trail in the HttpResponse class using reflector but I can't find any proof that confirms this suspicion. I think the answer lies within the HttpWriter class.
Another Update
It so happens that I'm currently reading the excellent book "Pro ASP.NET MVC Framework" by Steve Sanderson (buy it if you don't already have it). In chapter 10 he links to a post on his blog where he talks about partial output caching and the poor integration between the MVC framework and the output cache. I haven't tried the custom outputcache attribute in the post yet... I will try it out and let you know if it does anything to solve the problem.

Resources