尝试在静态方法中使用HttpContext.Session [英] Trying to use HttpContext.Session in a static method
问题描述
我有以下提供错误信息的方法
I have the following method that gives the error
非静态字段,方法或属性'HttpContext.Session'需要对象引用
An object reference is required for the non-static field, method, or property 'HttpContext.Session'
namespace Website.Controllers
{
// CONTROLLER CLASS IS HERE BUT REMOVED AS NOT RELEVANT CODE
public static class HtmlExtensions
{
public static decimal GetCartTotal()
{
decimal cartTotal = 0;
var storedData = HttpContext.Session.GetString(ShoppingCartTotal);
if (storedData != null)
{
cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
}
return cartTotal;
}
}
}
很显然,我知道我正在从静态方法中调用非静态调用,但是我不确定如何创建HttpContext.Session对象.我需要方法是静态的,因为我是从视图中调用该数据的.我无法在视图模型中传递数据,因为_Layout.cshtml页面上正在使用该数据,并且我不想进入并将其手动添加到每个视图模型并在每个控制器方法中对其进行分配.共享视图中在控制器中调用方法的最佳方法?
Obviously I understand I am calling a non static call from a static method, but I am not sure how to create an HttpContext.Session object. I need the method to be static as I am calling that data from the view. I can not pass the data in the view model as the data is being used on the _Layout.cshtml page and I do not want to go in and manually add it to every viewmodel and assign it in each controller method... What is the best way to call a method in the controller in a shared view?
在View中,我有以下可行的方法,但仅当它是静态方法时才有效,因为它是HttpContext不起作用的静态方法
I have the following in the View that works, but only when it is a static method, which because it is a static method that HttpContext is not working
@using Website.Controllers
@{
var ShoppingCartTotal = HtmlExtensions.GetCartTotal();
}
推荐答案
您应该从调用方传递方法的依赖项,最好是在方法中添加一个接受Session
对象输入和调用方的参数需要将其传递给:
You should be passing the dependencies of the method from the caller, better would be to add a parameter in the method that takes Session
object input and the caller would need to pass it in :
public static decimal GetCartTotal(HttpSessionState session)
{
decimal cartTotal = 0;
var storedData = session.GetString(ShoppingCartTotal);
if (storedData != null)
{
cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
}
return cartTotal;
}
希望有帮助!
正如@Scott的评论中所建议的那样,您也可以创建一个扩展方法,因为您已经在静态类中拥有了它,则可以这样编写:
As suggested in comments by @Scott, you could make an extension method as well, as you already have it in a static class you could write it like:
public static decimal GetCartTotal(this HttpSessionState session)
{
decimal cartTotal = 0;
var storedData = session.GetString(ShoppingCartTotal);
if (storedData != null)
{
cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
}
return cartTotal;
}
现在您可以在主叫方调用它,例如:
and now you can call it at calling side like:
var total = HttpContext.Session.GetCartTotal()
这篇关于尝试在静态方法中使用HttpContext.Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!