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 - Task Collaboration

Unlocking Efficiency and Collaboration: The Power of Asana Asana is a great place to start off as a small team and works well with teams at scale as I've seen. As an IT project manager, you understand the importance of streamlined workflows, efficient collaboration, and staying organized. In the world of project management and task tracking, Asana stands out as a powerhouse tool that can elevate your productivity with ease. With a short learning curve to get moving, it's easier than some more comprehensive tools to get started. 1. Projects: Structured Organization at Your Fingertips One of the main benefits of Asana is its project management capabilities. As a full-stack developer or a social media manager, you deal with numerous tasks and projects daily. Asana allows you to create and manage projects effortlessly. You can break down complex tasks into smaller, actionable steps, assign them to team members, and set due dates. This structured approach ensures that everyone know...