MVC 3 及更高版本包含 4 个集合的默认值提供程序:
Form
, RouteData
,QueryString
和File
.
Cookie 和服务器变量没有值提供程序。但似乎您可以为这些集合编写自己的价值提供者。
Cookie 示例:
public class CookieValueProviderFactory : ValueProviderFactory
{
public class CookieValueProvider : IValueProvider
{
private readonly HttpCookieCollection _cookies;
public CookieValueProvider(HttpCookieCollection cookies)
{
_cookies = cookies;
}
public bool ContainsPrefix(string prefix)
{
return _cookies.AllKeys.Any(x => x.Contains(prefix));
}
public ValueProviderResult GetValue(string key)
{
if (_cookies == null)
{
return null;
}
var val = _cookies[key] == null ? null : _cookies[key].ToString();
var val = _cookies[key];
return val != null
? new ValueProviderResult(val, val.ToString(), CultureInfo.CurrentCulture)
: null;
}
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
return new CookieValueProvider(controllerContext.HttpContext.Request.Cookies);
}
}
并在 global.asax 中注册:
protected void Application_Start()
{
...
ValueProviderFactories.Factories.Add(new CookieValueProviderFactory());
RegisterRoutes(...)
}