force mvc to use Custom Value Provider based on Cookies instead of default use of Querystring

616 Views Asked by At

I have a Custom Value Provider implemented. And I have a link with containing querystring something like

ads?lid=val

and my action definition

public async ReturnType ads(int lid=0)

I registered Value provider in Global.asax like

 ValueProviderFactories.Factories.Add(new Listhell.CODE.CustomValueProviderFactory());

But when I click on link on controller I get querystring value but not cookie's

How can make mvc to use custom value provider to pass cookie value to controller instead of default behavior?

1

There are 1 best solutions below

0
On

There are several built-in providers, like query string etc. These providers are invoked one by one from beggining of the chain, until some of them will be able to provide a value.

So you must register "CustomValueProviderFactory" on top of the default value providers chain by the following line of code:

ValueProviderFactories.Factories.Insert(0, new Listhell.CODE.CustomValueProviderFactory());

therefore your custom value provider is called first of all and you should get value from wherever you need. The following lines of code demonstrates how to get this value from cookie:

public class CookieValueProvider: IValueProvider
{
    public bool ContainsPrefix(string prefix)
    {
        return HttpContext.Current.Request.Cookies[prefix] != null;
    }

    public ValueProviderResult GetValue(string key)
    {
        if(HttpContext.Current.Request.Cookies[key] == null)
            return null;

        return new ValueProviderResult(HttpContext.Current.Request.Cookies[key],
            HttpContext.Current.Request.Cookies[key].ToString(), CultureInfo.CurrentCulture);
    }
}

hope that it helps.