当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC5网站开发之网站设置(九)

ASP.NET MVC5网站开发之网站设置(九)

2017年12月12日  | 移动技术网IT编程  | 我要评论
网站配置一般用来保存网站的一些设置,写在配置文件中比写在数据库中要合适一下,因为配置文件本身带有缓存,随网站启动读入缓存中,速度更快,而保存在数据库中要单独为一条记录创建一

网站配置一般用来保存网站的一些设置,写在配置文件中比写在数据库中要合适一下,因为配置文件本身带有缓存,随网站启动读入缓存中,速度更快,而保存在数据库中要单独为一条记录创建一个表,结构不够清晰,而且读写也没有配置文件容易实现。这次要做的是网站的基本信息,数据保存在siteconfig.config。

在14年的时候写过一篇博客《.net mvc 网站中配置文件的读写》 ,在那篇博客中把思路和方法都已经写清楚了,这次的实现思路和上次一样,只是那次自己实现了keyvalueelement类和keyvalueelementcollection类,其实这两个类在system.configuration命名空间中都已经实现,直接使用就行。 

一、网站配置类(siteconfig)

1、在nninesky.core项目新建文件夹config

2、在config文件夹添加类siteconfig。

using system.componentmodel.dataannotations;
using system.configuration;

namespace ninesky.core.config
{
 /// <summary>
 /// 网站配置类
 /// </summary>
 public class siteconfig : configurationsection
 {
 private static configurationproperty _property = new configurationproperty(string.empty, typeof(keyvalueconfigurationcollection), null, configurationpropertyoptions.isdefaultcollection);

 [configurationproperty("", options = configurationpropertyoptions.isdefaultcollection)]
 private keyvalueconfigurationcollection keyvalues
 {
 get { return (keyvalueconfigurationcollection)base[_property]; }
 set { base[_property] = value; }
 }


 /// <summary>
 ///网站名称
 /// </summary>
 [required(errormessage = "*")]
 [stringlength(50, errormessage = "最多{1}个字符")]
 [display(name = "网站名称")]
 public string sitename
 {
 get { return keyvalues["sitename"] == null? string.empty: keyvalues["sitename"].value; }
 set { keyvalues["sitename"].value = value; }
 }

 /// <summary>
 ///网站标题
 /// </summary>
 [required(errormessage = "*")]
 [stringlength(50, errormessage = "最多{1}个字符")]
 [display(name = "网站标题")]
 public string sitetitle
 {
 get { return keyvalues["sitetitle"] == null? string.empty: keyvalues["sitetitle"].value; }
 set { keyvalues["sitetitle"].value = value; }
 }

 /// <summary>
 ///网站地址
 /// </summary>
 [datatype(datatype.url)]
 [required(errormessage = "*")]
 [stringlength(500, errormessage = "最多{1}个字符")]
 [display(name = "网站地址")]
 public string siteurl
 {
 get { return keyvalues["siteurl"] == null ? "http://" : keyvalues["siteurl"].value; }
 set { keyvalues["siteurl"].value = value; }
 }

 /// <summary>
 ///meta关键词
 /// </summary>
 [datatype(datatype.multilinetext)]
 [stringlength(500, errormessage = "最多{1}个字符")]
 [display(name = "meta关键词")]
 public string metakeywords
 {
 get { return keyvalues["metakeywords"] == null ? string.empty: keyvalues["metakeywords"].value; }
 set { keyvalues["metakeywords"].value = value; }
 }

 /// <summary>
 ///meta描述
 /// </summary>
 [datatype(datatype.multilinetext)]
 [stringlength(1000, errormessage = "最多{1}个字符")]
 [display(name = "meta描述")]
 public string metadescription
 {
 get { return keyvalues["metadescription"] == null ? string.empty : keyvalues["metadescription"].value; }
 set { keyvalues["metadescription"].value = value; }
 }

 /// <summary>
 ///版权信息
 /// </summary>
 [datatype(datatype.multilinetext)]
 [stringlength(1000, errormessage = "最多{1}个字符")]
 [display(name = "版权信息")]
 public string copyright
 {
 get { return keyvalues["copyright"] == null ? "ninesky 版权所有" : keyvalues["copyright"].value; }
 set { keyvalues["copyright"].value = value; }
 }

 }
}

siteconfig类继承自configurationsection,继承自这个类是才能读写配置节。

在类中声明一个配置元素的子元素 private static configurationproperty _property,子元素的配置实体类型是keyvalueconfigurationcollection(键/值集合)。

复制代码 代码如下:
private static configurationproperty _property = new configurationproperty(string.empty, typeof(keyvalueconfigurationcollection), null, configurationpropertyoptions.isdefaultcollection);

然后徐再在类中声明一个属性private keyvalueconfigurationcollection keyvalues。利用keyvalues获取、设置配置节键/值集合。

 [configurationproperty("", options = configurationpropertyoptions.isdefaultcollection)]
 private keyvalueconfigurationcollection keyvalues
 {
 get { return (keyvalueconfigurationcollection)base[_property]; }
 set { base[_property] = value; }
 } 

然后就可以使用keyvalues[“name”]获取设置具体配置了。 

/// <summary>
 ///网站名称
 /// </summary>
 [required(errormessage = "*")]
 [stringlength(50, errormessage = "最多{1}个字符")]
 [display(name = "网站名称")]
 public string sitename
 {
 get { return keyvalues["sitename"] == null? string.empty: keyvalues["sitename"].value; }
 set { keyvalues["sitename"].value = value; }
 }

 

看起来是不是跟其他模型类差不多,知识get;set;有所不同。

二、设置配置文件的类型和路径 

打开nniesky.web项目的 web.config文件,找到configsections,然后添加siteconfig配置节 

红框部分为添加类型,说明了配置节的名称和类型,注意红线部分,restartonexternalchanges设为"false",如果不设置,配置文件修改后会重启网站。 

在配置文件的结尾</configuration>添加配置文件的路径 

图中红框部分为添加内容,指明siteconfig的位置文件在网站目录config文件夹下名为siteconfig.config的文件。 

然后在项目中添加config文件夹,然后添加名为siteconfig.config的配置文件。

<?xml version="1.0" encoding="utf-8"?>
<siteconfig>
 <add key="sitename" value="ninesky" />
 <add key="sitetitle" value="1133" />
 <add key="siteurl" value="http://mzwhj.cnblogs.com" />
 <add key="metakeywords" value="关键词," />
 <add key="metadescription" value="描述" />
 <add key="copyright" value="ninesky 版权所有<a>11</a>" />
</siteconfig>

配置文件中的键名与siteconfig的属性名对应。 

三、控制器和视图
1、配置文件的读取

在ninesky.web/areas/control/controllers【右键】->添加->控制器,输入控制器名configcontroller。 

在控制其中添加方法siteconfig方法 

/// <summary>
 /// 站点设置
 /// </summary>
 /// <returns></returns>
 public actionresult siteconfig()
 {
 siteconfig _siteconfig = system.web.configuration.webconfigurationmanager.openwebconfiguration("~").getsection("siteconfig") as ninesky.core.config.siteconfig;
 return view(_siteconfig);
 }

代码很简单,利用webconfigurationmanager的getsection方法就将配置信息读出来了。 

右键添加视图,将个属性显示出来。 

@model ninesky.core.config.siteconfig

@{
 viewbag.title = "站点设置";
}

@section sidenav{@html.partial("sidenavpartialview")}

<ol class="breadcrumb">
 <li><span class="glyphicon glyphicon-home"></span> @html.actionlink("首页", "index", "home")</li>
 <li>@html.actionlink("系统设置", "index")</li>
 <li class="active">站点设置</li>
</ol>

@using (html.beginform())
{
 @html.antiforgerytoken()
 
 <div class="form-horizontal">
 @html.validationsummary(true, "", new { @class = "text-danger" })

 <div class="form-group">
 @html.labelfor(model => model.sitename, htmlattributes: new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @html.editorfor(model => model.sitename, new { htmlattributes = new { @class = "form-control" } })
 @html.validationmessagefor(model => model.sitename, "", new { @class = "text-danger" })
 </div>
 </div>

 <div class="form-group">
 @html.labelfor(model => model.sitetitle, htmlattributes: new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @html.editorfor(model => model.sitetitle, new { htmlattributes = new { @class = "form-control" } })
 @html.validationmessagefor(model => model.sitetitle, "", new { @class = "text-danger" })
 </div>
 </div>

 <div class="form-group">
 @html.labelfor(model => model.siteurl, htmlattributes: new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @html.editorfor(model => model.siteurl, new { htmlattributes = new { @class = "form-control" } })
 @html.validationmessagefor(model => model.siteurl, "", new { @class = "text-danger" })
 </div>
 </div>

 <div class="form-group">
 @html.labelfor(model => model.metakeywords, htmlattributes: new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @html.editorfor(model => model.metakeywords, new { htmlattributes = new { @class = "form-control" } })
 @html.validationmessagefor(model => model.metakeywords, "", new { @class = "text-danger" })
 </div>
 </div>

 <div class="form-group">
 @html.labelfor(model => model.metadescription, htmlattributes: new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @html.editorfor(model => model.metadescription, new { htmlattributes = new { @class = "form-control" } })
 @html.validationmessagefor(model => model.metadescription, "", new { @class = "text-danger" })
 </div>
 </div>

 <div class="form-group">
 @html.labelfor(model => model.copyright, htmlattributes: new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @html.editorfor(model => model.copyright, new { htmlattributes = new { @class = "form-control" } })
 @html.validationmessagefor(model => model.copyright, "", new { @class = "text-danger" })
 </div>
 </div>

 <div class="form-group">
 <div class="col-md-offset-2 col-md-10">
 <input type="submit" value="保存" class="btn btn-default" />
 </div>
 </div>
 </div>
}

2、配置文件的保存。 

在控制器中再添加一个[httppost]类型的siteconfig方法。 

[validateinput(false)]
 [validateantiforgerytoken]
 [httppost]
 public actionresult siteconfig(formcollection form)
 {
 siteconfig _siteconfig = system.web.configuration.webconfigurationmanager.openwebconfiguration("~").getsection("siteconfig") as ninesky.core.config.siteconfig;
 if (tryupdatemodel<siteconfig>(_siteconfig))
 {
 _siteconfig.currentconfiguration.save();
 return view("prompt", new prompt() { title = "修改成功", message = "成功修改了网站设置", buttons = new list<string> { "<a href='"+url.action("siteconfig") +"' class='btn btn-default'>返回</a>" } });
 }
 else return view(_siteconfig);
 }
 }

代码也非常简单,与读取配置文件相同,使用webconfigurationmanager的getsection方法将配置信息读入_siteconfig中,然后用tryupdatemodel<siteconfig>(_siteconfig)绑定视图提交过来的信息。 

如果绑定成功,利用_siteconfig.currentconfiguration.save()方法保存配置信息(这个方法继承自configurationsection,不用自己实现)。 

效果如下图

=================================================
 代码下载: 
下载方法:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网