Need Help understanding this code - asp.net-mvc

I am trying to learn unit testing. I am trying to unit test some Memembership stuff I am making in asp.net mvc 1.0. I been following a book on MVC and I am confused about some stuff that hopefully someone can clear up for me.
I am using Nunit and Moq for my frameworks.
Question 1:
public AuthenticationController(IFormsAuthentication formsAuth, MembershipProvider provider)
{
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
Provider = provider ?? Membership.Provider;
}
I am kinda confused what "??" does I never really seen it before. Like I don't even know whats happening really in here. Like they passin the interface and then "??" mark happens and makes a new FormsAuthenticationWraper is made?
Question 2.
public AuthenticationController(): this(null, null)
{
}
I know this is the default constructor but I am not sure why ": this(null,null)" is doing.
Like what is it implementing? and what is this refering too. And on top of it why can't that be just left out? And just stick the default constructor as it is.
Question 3.
In the book(asp.net mvc 1.0 quickly) it talks about how it would be quite a bit of work to implementing the Memembership provider would be alot of work. So they use moq mockup framework to make life easier.
Now my question is they don't use the moq on the "FormsAuthentication". They instead make an interface
public interface IFormsAuthentication
{
void SetAuthCookie(string userName, bool createPersistentCookie);
void SignOut();
}
Then make a wrapper
public class FormsAuthenticationWrapper : IFormsAuthentication
{
public void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
Then finally a property
public IFormsAuthentication FormsAuth
{
get;
private set;
}
Where as with the membership they only have
public static MembershipProvider Provider
{
get;
private set;
}
I am not sure though what to change the stuff too. Like what would I change this line too?
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
I also tried to add another method into the FormsAuthentication Interface and Wrapper.
public void RedirectFromLoginPage(string userName, bool createPersistentCookie)
{
FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie);
}
Yet I am not sure what is happening but my unit test always fails does not matter what I try to do to fix it.
public ActionResult Login(string returnUrl, FormCollection form, bool rememberMe)
{
LoginValidation loginValidation = new LoginValidation();
try
{
UpdateModel(loginValidation, form.ToValueProvider());
}
catch
{
return View("Login");
}
if (ModelState.IsValid == true)
{
bool valid = authenticate.VerifyUser(loginValidation.UserName, loginValidation.Password);
if (valid == false)
{
ModelState.AddModelError("frm_Login", "Either the Password or UserName is invalid");
}
else if (string.IsNullOrEmpty(returnUrl) == false)
{
/* if the user has been sent away from a page that requires them to login and they do
* login then redirect them back to this area*/
return Redirect(returnUrl);
}
else
{
FormsAuth.RedirectFromLoginPage(loginValidation.UserName, rememberMe);
}
}
return View("Login");
Here is my test
[Test]
public void Test_If_User_Is_Redirected_Back_To_Page_They_Came_From_After_Login()
{
System.Diagnostics.Debugger.Break();
var formsAuthenticationMock = new Mock<AuthenticationController.IFormsAuthentication>();
var membershipMock = new Mock<MembershipProvider>();
membershipMock.Setup(m => m.ValidateUser("chobo2", "1234567")).Returns(true);
// Setup controller
AuthenticationController target = new AuthenticationController(formsAuthenticationMock.Object, membershipMock.Object);
// Execute
FormCollection form = new FormCollection();
form.Add("Username", "chobo2");
form.Add("password", "1234567");
ViewResult actual = target.Login(null, form, false) as ViewResult;
Assert.That(actual.View, Is.EqualTo("home"));
formsAuthenticationMock.Verify();
}
Actual always comes back to null. I tried ViewResult, RedirectResult and RedirectToRouteResult but everyone comes back null. So I am not sure why this is happening since I find it weird first that
FormsAuth.RedirectFromLoginPage(loginValidation.UserName, rememberMe);
Does not stop the view and starts to redirect. I thought at first once it hits this line it is like a return statement and thats it no other code will be executed but htis does not seem to be the case so I am not sure if this could be the problem.
Thanks

Question 1
The ?? is called the null-coalescing operator, and is a very useful feature of C# 2.0 onwards.
In your case,
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
simply means "assign formsAuth to FormsAuth unless it is null, in which case assign new FormsAuthenticationWrapper()". It's basically a way of preventing null references in your code. You can also think of it as a shortcut for the following conditional expression:
FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
Question 2
The use of this(null, null) is called constructor chaining. All this means is that that the constructor in the same class (hence this, as opposed to base for the parent class) that takes two parameters, should be called before the body of the constructor is executed.
Overloading constructors is a common practice to make it easier for the developer to create new objects when they just want to use the default properties/settings.
Question 3
As others have mentioned, this really belongs as a separate question. Unlike the previous two, it's much more specific to the context/your code, rather than language features of C#.
Update
Ok, what I've done now is actually rewritten the two constructors here, since I think putting them in another (virtually equivalent) form might be a bit clearer, and is probably better design practice too. The null coalescing operator isn't necessary here.
public AuthenticationController()
: this(new FormsAuthenticationWrapper(), Membership.Provider)
{
}
public AuthenticationController(IFormsAuthentication formsAuth,
MembershipProvider provider)
{
this.FormsAuth = formsAuth;
this.Provider = provider;
}
In this form, it should be obvious that the constructor that takes two parameters simply assigns the class variables to the values of the arguments. The parameterless constructor (often called the default constructor) simply creates a new object using the default FormsAuth and Provider objects, which are specified via constructor chaining.

Question 1: ?? is the null coalescing operator. The ?? operator checks whether the value provided on the left side of the expression is null, and if so it returns an alternate value indicated by the right side of the expression.
In your situation, it checks if formsAuth is null, and returns a new FormsAuthenticationWrapper() if it is null.

The ?? operator is saying "use this, unless it's null, it which case use this other thing".
So, this line of code:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
Is the same as:
if ( formsAuth != null ) FormsAuth = formsAuth
else FormsAuth = new FormsAuthenticationWrapper();

In answer to Q2
It is overloading the constructor.
If means that calling
Foo()
is the same as calling
Foo(null, null)

Question 1:
The ?? operator simply says "take whatever is on my left if it's not null - if it is, take whatever is on my right". So your code:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
is equivalent to
if (formsAuth != null) {
FormsAuth = formsAuth;
} else {
FormsAuth 0 new FormsAuthenticationWrapper();
}
Question 2: The :this(null, null) syntax is shorthand for "constructor inheritance" (my naming...). Your code
public AuthenticationController(): this(null, null)
{
}
public AuthenticationController(IFormsAuthentication formsAuth, MembershipProvider provider)
{
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
Provider = provider ?? Membership.Provider;
}
is equivalent to
public AuthenticationController()
{
FormsAuth = new FormsAuthenticationWrapper();
Provider = Membership.Provider;
}
public AuthenticationController(IFormsAuthentication formsAuth, MembershipProvider provider)
{
FormsAuth = formsAuth;
Provider = provider;
}

Question 2
public AuthenticationController(): this(null, null)
{
}
The no parameter constructor for AuthenticationController will call the constructor that takes a IFormsAuthentication and a MembershipProvider, passing two null values (this is done before any code in the no-param constructor code block is executed).
Since the two argument constructor uses the null-coalescing (??) operator to assign the variables and the passed arguments are null, a new MembershipProvider is used along with Membership.Provider object.
Had this constructor not been explicitly defined, the default no-param constructor would have been used. This could lead to unexpected behaviour if a new AuthenticationController was created (without passing any arguments to the constructor), since the member variables would not have been initialised.

Question 1:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
Provider = provider ?? Membership.Provider;
is equals to:
FormsAuth = (formsAuth == null ? new FormsAuthenticationWrapper() : formsAuth);
Provider = (provider == null ? Membership.Provider : provider);
Question 2:
It's just passing null to both formsAuth and provider constructor arguments. It's not good practice IMHO. Another constructor with no arguments would be a better fit.
EDIT: This makes no sense. Sorry, I was in a hurry and didn't really realize it was a constructor calling another constructor.
I don't have time to answer question 3 right now, I'll get to that later...

Related

Derived from AuthorizeAttribute but User.Identity.Name is null unless using AuthorizeAttribute

So I've created a custom authorize attribute I use in a few places that is derived from an abstract base class which is derived from AuthorizeAttribute:
CustomAuthorizeAttributeBase.cs
public abstract class CustomAuthorizeAttributeBase : AuthorizeAttribute
{
public abstract string GetUsers();
public abstract string GetRoles();
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.IsChildAction)
{
return;
}
filterContext.Result =
new RedirectToRouteResult(new RouteValueDictionary
{
{"controller", "NotAuthorized"},
{"action", "Index"},
});
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (GetUsers().IndexOf(httpContext.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
GetRoles().Split(',').Any(s => httpContext.User.IsInRole(s)))
{
return true;
}
return false;
}
}
AreaLevelReadonly.cs
public class AreaLevelReadOnly : CustomAuthorizeAttributeBase
{
public override string GetUsers()
{
return ConfigurationManager.AppSettings["AreaReadonlyUsers"];
}
public override string GetRoles()
{
return ConfigurationManager.AppSettings["AreaReadonlyRoles"];
}
}
I also have some fairly simple code that gets me the currently logged in user:
UserIdentity.cs
public class UserIdentity : IUserIdentity
{
public string GetUserName()
{
return HttpContext.Current.User.Identity.Name.Split('\\')[1];
}
}
However, when I add my AreaLevelReadonly attribute to my controllers, getUserName fails and returns an exception that Name is null. I agonized over it for about an hour before putting authorize attribute on there as well, at which point it magically started working again. So, what is so different on the implementation level that my attribute deriving from authorizeattribute doesn't cause the Name to be populated.
Note: Windows authentication is on for the area, and the code works, but I don't understand why the Readonly attribute isn't enough to trigger authorization and population of the HttpContext.Current.User.Identity.Name.
Edit: Working:
[AreaLevelReadonly]
[Authorize]
public class DeleteAreaDataController : Controller {
//etc
var username = _userIdentity.GetUserName(HttpContext);
//etc
}
Exception on name:
[AreaLevelReadonly]
public class DeleteAreaDataController : Controller {
//etc
var username = _userIdentity.GetUserName(HttpContext);
//etc
}
More likely than not, you're accessing User.Identity.Name before it's populated. By including the standard Authorize attribute, as well, your code is then only running after the user has been authorized already and User.Identity.Name has been populated.
EDIT
Sorry, I misunderstood where the code attempting to call User.Identity.Name was running. Based on the belief that it was happening in your custom attribute, I was suggesting that you're trying to access it too early. However, I now see that you're calling it in your controller (although an explanation of what happens in GetUserAccount(HttpContext) would have helped.)
Anyways, your custom attribute obviously adds extra conditions on whether a user is authorized or not. When you return false, there is no user. It's not a situation where the user is "logged in" but not allowed to see the page. It's either there or it isn't. So the user is failing authorization based on your custom attribute (User.Identity.Name is null) but is authorized when you include Authorize (User.Identity.Name has a value).
Long and short, your GetUserName or GetUserAccount or whatever code needs to account for when the user has failed authorization. Or, if the user shouldn't be failing authorization, you'll need to look into why your custom attribute isn't working. Though, either way, you should still account for User.Identity.Name being null.
Your custom attribute is probably reading User.Identity.Name before you check that the user is authenticated.
In other words, in IsAuthorized(), before you read User.Identity.Name, you should be doing something like this:
if (!user.Identity.IsAuthenticated)
{
// Your custom code...
return false;
}
The reason you need this is because Windows Authentication (at least for NTLM) is a 2-step negotiation process between the client and server (see https://support.citrix.com/article/CTX221693). There will be 2 requests - the first with no name, and the second with a name. You can test this yourself - the source code for AuthorizeAttribute is provided here. Copy/paste that into your code and put a breakpoint in IsAuthorized - you will see that the breakpoint is hit twice. First time, the name is null, second time, it's set to your username.
So I think the solution is to either check user.Identity.IsAuthenticated at the start of your method, if you need to run custom code (as shown above), or alternatively if you only need to return false, simply replace the above code with base.IsAuthorized() which should do it for you.

Ninject Call Method to Return Constructor Argument

I'm trying to bind a service and specifying a constructor argument using Ninject in our application. The constructor argument is a value that can be pulled from the query string or a cookie. The code we currently have is something like this
kernel.Bind<SomeService>()
.ToSelf()
.InRequestScope()
.WithConstructorArgument("someID", ctx =>
// Try to get it from the posted form values
System.Web.HttpContext.Current.Request.Form["someID"] != null ?
long.Parse(System.Web.HttpContext.Current.Request.Form["someID"]) :
// Try to get it from the query string
System.Web.HttpContext.Current.Request.QueryString["someID"] != null ?
long.Parse(System.Web.HttpContext.Current.Request.QueryString["someID"])
: 0);
This works but is pretty ugly. I realize there are other ways of accomplishing this such as passing in the Form value or the QueryString value as a parameter, but we like having it defined in the Binding. What we would ideally like to do is something like this:
kernel.Bind<SomeService>()
.ToSelf()
.InRequestScope()
.WithConstructorArgument("someID", ctx => GetSomeID());
From what I can tell, this is not possible. Is there another way to break out the constructor argument injection logic into another method so we don't have to nested one line if statements?
I'd suggest binding the dependency on the Query String / HTTP form via an interface. This approach seems more in line with the dependency injection pattern (de-coupling code from specific implementations and classes).
public interface IParameters
{
string SomeID { get; }
}
public class ParametersFromHttpContext
{
IQueryString _queryString;
IRequestForm _requestForm;
public ParametersFromHttpContext(IQueryString queryString, IRequestForm requestForm)
{
_queryString = queryString;
_requestForm = requestForm;
}
public string SomeID
{
get
{
return
// Try to get it from the posted form values
_requestForm["someID"] != null ?
long.Parse(_requestForm["someID"]) :
// Try to get it from the query string
_queryString["someID"] != null ?
long.Parse(_queryString["someID"])
: 0;
}
}
}
Now logic you want can be contained in the binding, without the need to reference HttpContext in the kernel.
kernel.Bind<IParameters>().To<ParametersFromHttpContext>();

how to unit test for session variable in controller in mvc

I am unit-testing my controller.
In one of my controller methods I am setting Session variables:
public void Index()
{ Session["foo"] = "bar";
return View();
}
How can I unit-test this? The problem is that the Session property is null when testing. Injecting is not possible because the Session property is readonly.
I don't want to use any third-party tool or mocking.
Simply dont use things like Session["foo"] in your controller methods. Best practice is keep action methods unaware of any context-like global objects. Everything your action method needs should be given to her in form of arguments. Note that built-in mechanism of model binding works exactly like that - you dont use Request.Form[], you let "somebody behind the scene" pass it to your action as argument.
Now for the session you can do the same - write you very simple ValueProvider which will know how to recognize arguments you want to fill from session, and you are done. In production your actions will work with session, in test you cant simply pass them any values you want as arguments.
For inspiration look at this http://www.prideparrot.com/blog/archive/2012/7/how_to_create_a_custom_session_value_provider
Injecting is not possible because the Session property is readonly.
This means you cannot use setter injection, but could you use constructor injection, ie add a constructor for your controller that is something like:
MyController(Session session)
{
m_session = session;
// then call your main constructor
}
Session getSession()
{
return m_session;
}
You can then use this separate constructor during testing.
I agree with #rouen. do not directly use Session["foo"]. But I think having ValueProvider ans might not be a practical solution, as we only store very few variables, and these values may be and most likely not ur full model.
So my approach is something similar to what Vic Smith suggests but a much more IOC (and Mock) friendly.
I would create a provider (i.e a service) to retrieve the session variables
public class SessionVariableProvider : ISessionVariableProvider
{
public object GetSessionValue(string key)
{
if (!HttpContext.Current.Session.IsNewSession
&& HttpContext.Current.Session[key] != null)
{
return HttpContext.Current.Session[key];
}
throw new ArgumentNullException(key);
}
public void SetSessionValue(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
}
public interface ISessionVariableProvider
{
object GetSessionValue(string key);
void SetSessionValue(string key, object value);
}
Modify your Controller expect ISessionVariableProvider as a parameter.
public class TestController: Controller
{
protected readonly ISessionVariableProvider _sessionVariableProvider;
protected InowiaControllerBase(ISessionVariableProvider sessionVariableProvider)
{
Guard.ArgumentNotNull(sessionVariableProvider, "sessionVariableProvider");
this._sessionVariableProvider = sessionVariableProvider;
}
public ActionResult Index()
{
_sessionVariableProvider.SetSessionValue("foo", "bar");
var foo2 = (string)_sessionVariableProvider.GetSessionValue("foo2");
return View();
}
}
when testing create your own test implementation of ISessionVariableProvider and pass it to the controller.

Session is null in RouteHandler

I have spent quite some time going through similar questions here and have not found any that answer my question - apologies if this is a duplicate however I'm pretty sure it's not..
I have an website where the aim is for visitors to complete a form. I am interested in testing different type of forms to ascertain which get filled out more consistently. My idea is that each form has it's own controller and when the user first requests the url it is picked up by a custom route handler which picks 1 form at random and set the relevant controller in RouteData. The chosen formid is then stored in the Session so on subsequnt requests instead of a form being picked at random it will just use the one from the session.
The probem is that I cannot seem to access the Session data in the routehandler - requestContext.Httpcontext.Session is always null. Is this because it is too early in the pipeline? if so how could I achieve this approach?
The first code I tried looked like this:
int FormID = 0;
string FormName = "";
RepositoryManager mgr = new RepositoryManager();
if (requestContext.HttpContext.Session["Form_ID"] != null && requestContext.HttpContext.Session["Form_Name"] != null)
{
int.TryParse(requestContext.HttpContext.Session["Form_ID"].ToString(), out FormID);
FormName = requestContext.HttpContext.Session["Form_Name"].ToString();
}
if (FormID == 0)
{
List<Form> forms = mgr.FormRepository.Get(f => f.FormType.Code == "").ToList();
int rnd = new Random().Next(0, forms.Count - 1);
FormID = forms[rnd].ID;
FormName = forms[rnd].FormName;
requestContext.HttpContext.Session["Form_ID"] = FormID;
requestContext.HttpContext.Session["Form_Name"].ToString();
}
requestContext.RouteData.Values["controller"] = FormName;
return new MvcHandler(requestContext);
This always errored as requestContext.HttpContext.Session is null
I have tried with a custom routehandler then passing off to a custom http handler as follows:
Routehandler
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext));
IHttpHandler handler = new FormMvcHandler(requestContext);
return handler;
FormMVCHandler
public class FormMvcHandler : MvcHandler, IRequiresSessionState
{
public FormMvcHandler(RequestContext requestContext)
: base(requestContext)
{
}
protected override void ProcessRequest(HttpContext httpContext)
{
//for testing setting form manually - session will be used here as in original routehandler
RequestContext.RouteData.Values["controller"] = "1Stage";
base.ProcessRequest(httpContext);
}
}
In this second approach changing the controller name has no effect. I have tried changing the controller name in the constructor of the HTTPHandler which does have an effect however If I try and access the session from there using RequestContext.HttpContext.Session it is still null. I have tried setting a breakpoint in ProcessRequest however it is never hit.
Edit 2
This now works by overriding both ProcessRequest(HttpContext httpContext) and BeginProcessRequest(HttpContext httpContext) in the HttpHandler - even when not using an async controller BeginProcessRequest is called by the framework (v3)
In your RouteHandler you have an function GetHttpHandler which return an IHttpHandler. That custom HttpHandler must use IRequiresSessionState and then you can access the Session in the ProcessRequest function in the HttpHandler.
Look into this post:
IRequiresSessionState - how do I use it?
I think you need to use IRequiresSessionState interface
It's too early to using Session in router hander.
you can achieve what you want by using action filter.
Create a Controller named FormController, an action named FormPickerAttribute. In the ActionExecuting of attribute, you can check cookie or session, where your set form id. let's say the form id is "Form1"(create one if null), then you change the action methods to "Form1".
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary{
{ "controller", "Form" },
{ "action", "Form1" },
{ "area", ""}, #your area name
{ "parameter", "parameter value"} #passing any parameter to the action
}
);
you can also create a controller for each form, just updated the
{"controller", "FormIdController"}
to the correct one.

What is needed in the HttpContext to allow FormsAuthentication.SignOut() to execute?

I am trying to write a unit test for our log out method. Among other things it FormsAuthentication.SignOut(). However, it throws a System.NullReferenceException.
I've created a mock; HttpContext (using Moq), but it is obviously missing something.
My mock context contains:
A mocked HttpRequestBase on Request
A mocked HttpResponseBase on Response
With a HttpCookieCollection on Request.Cookies and another on Response.Cookies
A mocked IPrincipal on User
I am aware I could go the wrapper route and inject an empty FormsAuth wrapper object in it's place, but I would really like to avoid the 3 additional files just to fix one line of code. That and I am still curious for an answer
So my question is "What is needed in the HttpContext to allow FormsAuthentication.SignOut() to execute."
The NullReferenceException in this case is actually being thrown by the call:
current.Request.Browser["supportsEmptyStringInCookieValue"]
You can test this assertion by calling:
HttpContext.Current.Request.Browser.SupportsEmptyStringInCookieValue
...which will also return the NullReferenceException. Contrary to the accepted answer, if you attempt to call:
CookielessHelperClass.UseCookieless(current, false, CookieMode)
...from the immediate window, this will return without error.
You can fix the exception like this:
HttpContext.Current.Request.Browser = new HttpBrowserCapabilities() { Capabilities = new Dictionary<string, string> { { "supportsEmptyStringInCookieValue", "false" } } };
...and the FormsAuthentication.SignOut() call will now succeed.
You can always wrap FormsAuthentication.SignOut() into another method and stub / mock it.
Create IFormsAuthenticationWrap interface.
public interface IFormsAuthenticationWrap
{
void SignOut();
}
Create wrap class that implements IFormsAuthenticationWrap
public class FormsAuthenticationWrap : IFormsAuthenticationWrap
{
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
Your calling class is going to look something like this:
public class LogOutClass
{
private readonly IFormsAuthenticationWrap _formsAuthentication;
public LogOutClass() : this (new FormsAuthenticationWrap())
{
}
public LogOutClass(IFormsAuthenticationWrap formsAuthentication)
{
_formsAuthentication = formsAuthentication;
}
public void LogOutMethod()
{
// Code before SignOut
_formsAuthentication.SignOut();
// Code after SignOut
}
}
Now let's get to our test. You can stub / mock with Moq but I'm going to show here how you can do it manually.
Create your stub / mock class:
public class FormsAuthenticationStub : IFormsAuthenticationWrap
{
public void SignOut()
{
}
}
And the last write the test:
[TestMethod]
public void TestLogOutMethod()
{
var logOutClass = new LogOutClass(new FormsAuthenticationStub());
logOutClass.LogOutMethod();
}
Here's the code for signout.
public static void SignOut()
{
Initialize();
HttpContext current = HttpContext.Current;
bool flag = current.CookielessHelper.DoesCookieValueExistInOriginal('F');
current.CookielessHelper.SetCookieValue('F', null);
if (!CookielessHelperClass.UseCookieless(current, false, CookieMode) || current.Request.Browser.Cookies)
{
string str = string.Empty;
if (current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
{
str = "NoCookie";
}
HttpCookie cookie = new HttpCookie(FormsCookieName, str);
cookie.HttpOnly = true;
cookie.Path = _FormsCookiePath;
cookie.Expires = new DateTime(0x7cf, 10, 12);
cookie.Secure = _RequireSSL;
if (_CookieDomain != null)
{
cookie.Domain = _CookieDomain;
}
current.Response.Cookies.RemoveCookie(FormsCookieName);
current.Response.Cookies.Add(cookie);
}
if (flag)
{
current.Response.Redirect(GetLoginPage(null), false);
}
}
Looks like you need a CookielessHelperClass instance. Too bad it's internal and sealed - there's no way to mock it unless you're using TypeMock. +1 for wrapper suggestions :)
The wrapper is the clean way to go.
You mentioned in a comment that "this is going to be quite a big application", that's another argument to use the wrapper not the opposite. In a big application you want to have clear dependencies, and you want tests to be done easily.
You are trading clean dependencies that can be easily injected over obscure dependencies to the internal workings of asp.net in your tests.
On a different note: Use Reflector. I honestly don't know the inner dependencies of this specific part of asp.net, but you can clear any doubts with reflector.
Don't mock HttpContext, use a real one in your tests. This way you don't have to mock all these Http* stuff. You can use Ivonna and test your method directly, without mocking all these dependencies and getting mysterious exceptions.

Resources