2016-08-19 62 views
0

读取cookie与简单的旧ASP.NET读取cookie一样容易掌握HttpContext.Current.Request对象,但在DNX中不存在这样的对象。如何使用Microsoft.AspNet(DNX)

如何检查cookie值以更改它的响应?

public static string GetContentValueByKey(this Dictionary<string, string> content, string key) { 
    string value; 
    return content.TryGetValue(key, out value) ? value : key; 
} 

我现在想,基于cookie的值,仅返回key代替value ......在“老好天”我可以很容易做到:

public static string GetContentValueByKey(this Dictionary<string, string> content, string key) { 
    string value; 
    var cookies = HttpContext.Current.Request.Cookies; 
    var showKeysOnly = cookies["showonlykeys"] != null && cookies["showonlykeys"] == "yes"; 
    return showKeysOnly ? key : content.TryGetValue(key, out value) ? value : key; 
} 

,但我们不再有权访问这样的对象......在控制器之外访问Cookies有什么窍门?

回答

0

在ASP.NET Core中没有任何东西是静态的HttpContext.Current。你需要通过路径(从你的控制器到使用方法)或者使用依赖注入来获取HttpContext(通过IHttpContextAccessor,它需要在之前提供)。然后您可以使用httpContext.Request.Cookies.Get("showonlykeys")来获取该值。

+0

ps。 DNX有点过时,不再支持。更新到RTM! – Thomas

相关问题