【问题标题】:Unable to retrieve Application State in Model class无法在模型类中检索应用程序状态
【发布时间】:2012-11-04 00:53:18
【问题描述】:

我在一个 MVC 项目中遇到了一个问题,这个问题是关于从 Application State 对象中检索值。

我以这种方式在Global.axas.csApplication_Start() 方法中将一些值存储到应用程序状态中:

//var str = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
//Application["connString"] = str;

Application["connString"] = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());

我已经确定web.config的值已经通过调试成功检索到了。

在这一步之后,我尝试以这种方式在我的Model Class 之一中检索此值:

var conn = new SqlConnection(Application["connString"].ToString());

但是在这里我得到了一个NullReferenceException Object reference not set to an instance of an object.

现在这对我来说非常困惑,如果值已成功检索并存储在 Application_Start() 点的 AapplicationState 中,那么为什么它在我的模型类中不可用,ApplciatiopnSate 不可用整个应用程序?

【问题讨论】:

标签: .net asp.net-mvc application-state


【解决方案1】:

我的建议是不要将连接字符串保留在 Application 变量中。相反,您可以声明一个可以返回连接字符串的静态方法。将连接字符串存储在静态变量中,如下所示

public class Utility
{
    static string connectionString;    
    public static string GetConnectionString()
    {
        if(string.IsNullOrEmpty(connectionString))
            connectionString = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
        return connectionString;
    }
}

配置文件被缓存,从此不用担心每次调用方法时读取文件的性能

【讨论】:

  • 我把它放在那里的主要原因之一是你看到它是加密格式的,需要在使用前解密,所以我不希望这个readingdecryption每次必须以某种方法建立数据连接时都会发生这种情况,这会增加时间并且是多余的做法。
  • 感谢您提供替代方案,但即使配置文件被缓存,每次调用此方法时都必须调用 DecryptString 方法?我主要关心的是尽可能避免使用这种繁重的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 2022-08-17
  • 1970-01-01
  • 2011-03-30
  • 2021-11-04
  • 2012-04-03
  • 1970-01-01
相关资源
最近更新 更多