Skip to main content

MVC Value Providers - Cookie Value Providers

Asp.NET MVC - Value providers


What are value providers?

A Value provider is a class that ties into the request pipeline and gets values out for you,
now this is fine for simple requests like when someone submits a form on your site. 

The built in one is quite powerful and covers simple data types all the way to creating models for you.

But what if you require a value that's not part of the form data or the query string, for example a header or a cookie.
Then you'll need to find or write a custom value provider to get one of these values in your action.


So today we're going to build a Cookie Value provider


public class HttpCookieValueProvider : System.Web.Mvc.IValueProvider
    {
        private ControllerContext _context;

        public HttpCookieValueProvider ( ControllerContext context )
        {
            if ( context == null )
                throw new ArgumentNullException( "context" );

            this._context = context;
        }

        #region IValueProvider Members

        bool IValueProvider.ContainsPrefix ( string prefix )
        {
            return prefix.StartsWith( "C_", true, CultureInfo.CurrentCulture );
        }

        ValueProviderResult IValueProvider.GetValue ( string key )
        {
            if ( string.IsNullOrWhiteSpace( key ) ) return null;

            string[] segments = key.Remove( 0, 1 ).Split( new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries );

            if ( segments.Length == 0 )
                return null;

            HttpCookie cookie = this._context.HttpContext.Request.Cookies[segments[0]];

            if ( cookie == null )
                return null;

            if ( segments.Length < 2 )
                return new ValueProviderResult( cookie.Value, cookie.Value, CultureInfo.CurrentCulture );

            return new ValueProviderResult( cookie.Values.GetValues( segments[1] ), cookie.Values[segments[1]], CultureInfo.CurrentCulture );
        }

        #endregion
    }


Which basically Implements IValueProvider which can be found in the Mvc and Web Api namespaces. This Value provider above intends to get a value from a Request Cookie.

It checks your Mvc Action method for a parameter starting with C_ in this case then looks for a cookie with the name following C_(Name of the cookie here) 

Taking it a step further if you have a Cookie with more than one value use 
C_(Name of the cookie)_(Name of the value within the cookie you'd like to get)


Next hook to hook it up to MVC

We'll need a factory which will create a new instance of our Value Provider using the Controller Context


 public class HttpCookieValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider ( ControllerContext controllerContext )
        {
            return new HttpCookieValueProvider( controllerContext );
        }

    }


Lastly

In the Global.asax file inside the Application_Start() method, register


//Cookie Value Provider Custom
ValueProviderFactories.Factories.Add( new HttpCookieValueProviderFactory() );



And thats it you're done. Now you can just pull cookie values out of your action methods like

public ActionResult (string C_City){
}




Comments

Popular posts from this blog

Passing Additional View Data to a DisplayTemplate

Passing additional ViewData Asp.NET MVC Now as the name suggests, ViewData might get you thinking about just that. Whereas there's a quite simple way to get your extra data across to a Display or Editor Template . This time the simplest answer is the one, though not the obvious one. Pass across your additionalViewData like you normally would @Html.DisplayFor( modelItem => item.ImageId, new { Class = "thumb-sm" } ) Then access if from your template using a simple ViewBag dynamic object. File Path /Views/Shared/DisplayTemplates/TemplateName.cshtml In this case we're passing along an additional class intended to allow us to control the size of the image rendered on the page. Haven't tried this in older versions of MVC, this will work in 4 & 5 Hope this helps someone, thought I'd put it up here as I forgot and spent a few minutes searching my code for the answer.  Thanks for reading.

Get Started with Asana Projects - Your Gateway to Productivity

In our previous look at Asana as a scalable collaboration task tracker , we touched on its power to revolutionize your project management. Today, we'll take a closer look at one of the fundamental building blocks of Asana: Projects. The Heart of Asana: Projects In Asana, a project is what you think it is, holding all the tasks related to an initiative. Whether you're a full-stack developer tackling a new app release or a social media manager orchestrating a marketing campaign, projects are where you'll plan, track, and execute your work. Creating a Project Setting up a project in Asana is a breeze. Here's a guide to get you started: -  Click the "Create" Button in the left sidebar and a dropdown menu will appear. - Choose Project: From the dropdown menu, select "Project." You'll then be prompted to choose between a "List" or "Board" view for your project. You can easily change this later in Project Settings. - Name Your Projec...

Get Started with AngularJs using a WebApi backend

AngularJs & WebApi Getting started I'd found it quite a ride converting an .NET MVC3 web app over to Angular, especially with Auth,  the social login flow. So once I did I decided to put up a neatly packaged template on Github to get people started incase these things were holding them up as well. Get Started with my template  https://github.com/warrendodsworth/angular-webapi-start It's a working template app and I'd like to say that I welcome contributions, please keep the code lean and readable. This is a pretty old template now since Angular on Typescript came out. It was fun then and is a lot nicer now with Typescript. MVC3 has moved on to dotnet core for API building. PS I'll be adding to this post to explain the pieces of it a bit more, the same should be visible on the readme on Github.