簡體   English   中英

強制mvc使用基於Cookie的自定義值提供程序,而不是默認使用Querystring

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

我實現了一個自定義值提供程序。 而且我有一個包含查詢字符串的鏈接,例如

ads?lid=val

和我的動作定義

public async ReturnType ads(int lid=0)

我在Global.asax中注冊了價值提供者,例如

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

但是當我單擊控制器上的鏈接時,我得到的是querystring值,而不是cookie的

如何使MVC使用自定義值提供程序將Cookie值傳遞給控制器​​而不是默認行為?

有幾個內置的提供程序,例如查詢字符串等。這些提供程序從鏈開始時就被一個接一個地調用,直到其中一些能夠提供值為止。

因此,您必須通過以下代碼行在默認值提供程序鏈的頂部注冊“ CustomValueProviderFactory”:

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

因此,您的自定義值提供者首先被調用,您應該從任何需要的地方獲取價值。 以下代碼行演示了如何從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);
    }
}

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM