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
Post a Comment