这里有新鲜出炉的精品教程, 程序狗速度看过来!
ASP.NET
ASP.NET 是. NET FrameWork 的一部分, 是一项微软公司的技术, 是一种使嵌入网页中的脚本可由因特网服务器执行的服务器端脚本技术, 它可以在通过 HTTP 请求文档时再在 Web 服务器上动态创建它们 指 Active Server Pages(动态服务器页面) , 运行于 IIS(Internet Information Server 服务, 是 Windows 开发的 Web 服务器)之中的程序
这篇文章主要为大家详细介绍了 ASP.NET MVC5 网站开发之网站设置, 感兴趣的小伙伴们可以参考一下
网站配置一般用来保存网站的一些设置, 写在配置文件中比写在数据库中要合适一下, 因为配置文件本身带有缓存, 随网站启动读入缓存中, 速度更快, 而保存在数据库中要单独为一条记录创建一个表, 结构不够清晰, 而且读写也没有配置文件容易实现这次要做的是网站的基本信息, 数据保存在 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, 不用自己实现)
效果如下图
=================================================
代码下载: http://git.oschina.net/ninesky/Ninesky
下载方法: http://www.cnblogs.com/mzwhj/p/5729848.html
来源: http://www.phperz.com/article/18/0308/352552.html