I thought I would do a quick post about Creating and more importantly Deleting cookies in ASP.NET as it’s not quite as obvious as it may seem with the misleading .Remove() method which doesnt do as you would expect.
I hope this helps someone get started with cookies if your just getting started with the .NET framework.
Creating a cookie
This is a basic example of how to create a cookie in ASP.NET C#
//Create a new cookie, passing the name into the constructor
HttpCookie cookie = new HttpCookie("MyCookie");
//Set the cookies value
cookie.Value = "CookieValue";
//Set the cookie to expire in 1 day
cookie.Expires = DateTime.Now.AddDays(1);
//Add the cookie
Response.Cookies.Add(cookie);
Deleting a cookie
When deleting a cookie all you need to do is amend the HttpCookie object so it has an expiry date in the past, then re-save the cookie to push the new value to the client.
If you wan’t to allow hyphens in your URL’s you will need to change the way the routing works in your Global.asax file.
First create a new class which extends the MvcRouteHandler and place this in the Global.asax file after the main MvcApplication class.
C#:
public class HyphenatedRouteHandler : MvcRouteHandler{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext){
requestContext.RouteData.Values["controller"]= requestContext.RouteData.Values["controller"].ToString().Replace("-","_");
requestContext.RouteData.Values["action"]= requestContext.RouteData.Values["action"].ToString().Replace("-","_");return base.GetHttpHandler(requestContext);}}
VB:
Public Class HyphenatedRouteHandler
Inherits MvcRouteHandler
Protected Overrides Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler
requestContext.RouteData.Values("controller") = requestContext.RouteData.Values("controller").ToString.Replace("-", "_")
requestContext.RouteData.Values("action") = requestContext.RouteData.Values("action").ToString.Replace("-", "_")
Return MyBase.GetHttpHandler(requestContext)
EndFunctionEnd Class
Then you need to replace the routes.MapRoute with an equivalent routes.Add specifying the new handler as the MapRoute does not allow you to specify a custom route handler.
C#:
routes.Add(
new Route("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller ="Default", action ="Index", id =""}),
new HyphenatedRouteHandler()));
VB:
routes.Add(New Route("{controller}/{action}/{id}",
New RouteValueDictionary(NewWith {.controller = "Home", .action = "Index", .id = ""}),
New HyphenatedRouteHandler()))
I hope this is useful, any questions feel free to get in touch.
Would like to say thanks to John from here for answering the original question on Stackoverflow