asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了asp.net-mvc – MVC 3从web.config中的AppSettings获取值大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在正常的ASP.NET Web表单站点中,我将使用web.configs“appsetTings”将应用程序设置数据添加到站点。但是,当使用MVC 3时,我无法以这种方式检索设置值。

首先,有2个web.config文件。一个在网站的根目录,第二个列在Views区域。我假设我想把我的appsetTings信息放在根web.config文件中,是否正确? (把它放在另一个视图下似乎产生一个错误,指出“AppSetTings”只能在每个Web应用程序出现一次。)

当我尝试检索它(C#:System.Configuration.ConfigurationManager.AppSetTings [“SetTingName”])我得到一个空白或空/空返回值。我究竟做错了什么?

我应该提到,我实际上是在模型区域的一个类文件中检索这个信息,使用get设置一个模型的具体值;组;。在模型中我不可能做到这一点吗?

在Controller.cs中:

WindowsLiveConnect.serviceConfiguration WLSC = new WindowsLiveConnect.serviceConfiguration();

ViewBag.ClientID = SC.ClientID; // This returns empty

在web.config中

...

  <appSetTings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

    <add key="ClientID" value="0000000040062A3F" />
    <add key="ClientSecret" value="SUPERSECRETpassworD" />
    <add key="RedirectURL" value="http%3A%2F%2Fwww.quilnet.com" />
  </appSetTings>

...

在Model.cs文件中:

public class serviceConfiguration
        {
            private String clientid;
            private String clientsecret;
            private String redirecturl;

            public String ClientID
            {

                get { return clientid; }

                set
                {
                    clientid = System.Configuration.ConfigurationManager.AppSetTings["ClientID"];
                }
            }

            public String ClientSecret
            {

                get { return clientsecret; }

                set
                {
                    clientsecret = System.Configuration.ConfigurationManager.AppSetTings["ClientSecret"];
                }
            }

            public String RedirectURL
            {

                get { return redirecturl; }

                set
                {
                    redirecturl = System.Configuration.ConfigurationManager.AppSetTings["RedirectURL"];
                }
            }
        }

解决方法

通常我正在使用AppSetTings静态类来访问这些参数。这样的事情
public static class AppSetTings 
{

    public static String ClientSecret
    {
        get
        {
            return SetTing<String>("ClientSecret");
        }
    }

    private static T SetTing<T>(String Name)
    {
        String value = ConfigurationManager.AppSetTings[name];

        if (value == null)
        {
            throw new Exception(String.Format("Could not find setTing '{0}',",Name));
        }

        return (T)Convert.ChangeType(value,typeof(T),CultureInfo.InvariantCulturE);
    }
}

大佬总结

以上是大佬教程为你收集整理的asp.net-mvc – MVC 3从web.config中的AppSettings获取值全部内容,希望文章能够帮你解决asp.net-mvc – MVC 3从web.config中的AppSettings获取值所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。