ASP.NET?MVC5網(wǎng)站開發(fā)之網(wǎng)站設(shè)置(九)
網(wǎng)站配置一般用來保存網(wǎng)站的一些設(shè)置,寫在配置文件中比寫在數(shù)據(jù)庫中要合適一下,因?yàn)榕渲梦募旧韼в芯彺?,隨網(wǎng)站啟動(dòng)讀入緩存中,速度更快,而保存在數(shù)據(jù)庫中要單獨(dú)為一條記錄創(chuàng)建一個(gè)表,結(jié)構(gòu)不夠清晰,而且讀寫也沒有配置文件容易實(shí)現(xiàn)。這次要做的是網(wǎng)站的基本信息,數(shù)據(jù)保存在SiteConfig.config。
在14年的時(shí)候?qū)戇^一篇博客《.Net MVC 網(wǎng)站中配置文件的讀寫》 ,在那篇博客中把思路和方法都已經(jīng)寫清楚了,這次的實(shí)現(xiàn)思路和上次一樣,只是那次自己實(shí)現(xiàn)了KeyValueElement類和KeyValueElementCollection類,其實(shí)這兩個(gè)類在System.Configuration命名空間中都已經(jīng)實(shí)現(xiàn),直接使用就行。
一、網(wǎng)站配置類(SiteConfig)
1、在Nninesky.Core項(xiàng)目新建文件夾Config
2、在Config文件夾添加類SiteConfig。
using System.ComponentModel.DataAnnotations;
using System.Configuration;
namespace Ninesky.Core.Config
{
/// <summary>
/// 網(wǎng)站配置類
/// </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>
///網(wǎng)站名稱
/// </summary>
[Required(ErrorMessage = "*")]
[StringLength(50, ErrorMessage = "最多{1}個(gè)字符")]
[Display(Name = "網(wǎng)站名稱")]
public string SiteName
{
get { return keyValues["SiteName"] == null? string.Empty: keyValues["SiteName"].Value; }
set { keyValues["SiteName"].Value = value; }
}
/// <summary>
///網(wǎng)站標(biāo)題
/// </summary>
[Required(ErrorMessage = "*")]
[StringLength(50, ErrorMessage = "最多{1}個(gè)字符")]
[Display(Name = "網(wǎng)站標(biāo)題")]
public string SiteTitle
{
get { return keyValues["SiteTitle"] == null? string.Empty: keyValues["SiteTitle"].Value; }
set { keyValues["SiteTitle"].Value = value; }
}
/// <summary>
///網(wǎng)站地址
/// </summary>
[DataType(DataType.Url)]
[Required(ErrorMessage = "*")]
[StringLength(500, ErrorMessage = "最多{1}個(gè)字符")]
[Display(Name = "網(wǎng)站地址")]
public string SiteUrl
{
get { return keyValues["SiteUrl"] == null ? "http://" : keyValues["SiteUrl"].Value; }
set { keyValues["SiteUrl"].Value = value; }
}
/// <summary>
///Meta關(guān)鍵詞
/// </summary>
[DataType(DataType.MultilineText)]
[StringLength(500, ErrorMessage = "最多{1}個(gè)字符")]
[Display(Name = "Meta關(guān)鍵詞")]
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}個(gè)字符")]
[Display(Name = "Meta描述")]
public string MetaDescription
{
get { return keyValues["MetaDescription"] == null ? string.Empty : keyValues["MetaDescription"].Value; }
set { keyValues["MetaDescription"].Value = value; }
}
/// <summary>
///版權(quán)信息
/// </summary>
[DataType(DataType.MultilineText)]
[StringLength(1000, ErrorMessage = "最多{1}個(gè)字符")]
[Display(Name = "版權(quán)信息")]
public string Copyright
{
get { return keyValues["Copyright"] == null ? "Ninesky 版權(quán)所有" : keyValues["Copyright"].Value; }
set { keyValues["Copyright"].Value = value; }
}
}
}
Siteconfig類繼承自ConfigurationSection,繼承自這個(gè)類是才能讀寫配置節(jié)。
在類中聲明一個(gè)配置元素的子元素 private static ConfigurationProperty _property,子元素的配置實(shí)體類型是KeyValueConfigurationCollection(鍵/值集合)。
然后徐再在類中聲明一個(gè)屬性private KeyValueConfigurationCollection keyValues。利用keyValues獲取、設(shè)置配置節(jié)鍵/值集合。
[ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
private KeyValueConfigurationCollection keyValues
{
get { return (KeyValueConfigurationCollection)base[_property]; }
set { base[_property] = value; }
}
然后就可以使用keyValues[“name”]獲取設(shè)置具體配置了。
/// <summary>
?///網(wǎng)站名稱
?/// </summary>
?[Required(ErrorMessage = "*")]
?[StringLength(50, ErrorMessage = "最多{1}個(gè)字符")]
?[Display(Name = "網(wǎng)站名稱")]
?public string SiteName
?{
?get { return keyValues["SiteName"] == null? string.Empty: keyValues["SiteName"].Value; }
?set { keyValues["SiteName"].Value = value; }
?}看起來是不是跟其他模型類差不多,知識(shí)Get;Set;有所不同。
二、設(shè)置配置文件的類型和路徑
打開Nniesky.web項(xiàng)目的 web.config文件,找到configSections,然后添加SiteConfig配置節(jié)

紅框部分為添加類型,說明了配置節(jié)的名稱和類型,注意紅線部分,restartOnExternalChanges設(shè)為"false",如果不設(shè)置,配置文件修改后會(huì)重啟網(wǎng)站。
在配置文件的結(jié)尾</configuration>添加配置文件的路徑

圖中紅框部分為添加內(nèi)容,指明SiteConfig的位置文件在網(wǎng)站目錄Config文件夾下名為SiteConfig.config的文件。
然后在項(xiàng)目中添加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="關(guān)鍵詞," /> <add key="MetaDescription" value="描述" /> <add key="Copyright" value="Ninesky 版權(quán)所有<a>11</a>" /> </SiteConfig>
配置文件中的鍵名與SiteConfig的屬性名對(duì)應(yīng)。
三、控制器和視圖
1、配置文件的讀取
在Ninesky.Web/Areas/Control/Controllers【右鍵】->添加->控制器,輸入控制器名ConfigController。
在控制其中添加方法SiteConfig方法
/// <summary>
/// 站點(diǎn)設(shè)置
/// </summary>
/// <returns></returns>
public ActionResult SiteConfig()
{
SiteConfig _siteConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~").GetSection("SiteConfig") as Ninesky.Core.Config.SiteConfig;
return View(_siteConfig);
}
代碼很簡(jiǎn)單,利用WebConfigurationManager的GetSection方法就將配置信息讀出來了。

右鍵添加視圖,將個(gè)屬性顯示出來。
@model Ninesky.Core.Config.SiteConfig
@{
ViewBag.Title = "站點(diǎn)設(shè)置";
}
@section SideNav{@Html.Partial("SideNavPartialView")}
<ol class="breadcrumb">
<li><span class="glyphicon glyphicon-home"></span> @Html.ActionLink("首頁", "Index", "Home")</li>
<li>@Html.ActionLink("系統(tǒng)設(shè)置", "Index")</li>
<li class="active">站點(diǎn)設(shè)置</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、配置文件的保存。
在控制器中再添加一個(gè)[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 = "成功修改了網(wǎng)站設(shè)置", Buttons = new List<string> { "<a href='"+Url.Action("SiteConfig") +"' class='btn btn-default'>返回</a>" } });
}
else return View(_siteConfig);
}
}
代碼也非常簡(jiǎn)單,與讀取配置文件相同,使用WebConfigurationManager的GetSection方法將配置信息讀入_siteConfig中,然后用TryUpdateModel<SiteConfig>(_siteConfig)綁定視圖提交過來的信息。
如果綁定成功,利用_siteConfig.CurrentConfiguration.Save()方法保存配置信息(這個(gè)方法繼承自ConfigurationSection,不用自己實(shí)現(xiàn))。
效果如下圖

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- ASP.NET MVC5網(wǎng)站開發(fā)之實(shí)現(xiàn)數(shù)據(jù)存儲(chǔ)層功能(三)
- ASP.NET?MVC5網(wǎng)站開發(fā)咨詢管理的架構(gòu)(十一)
- ASP.NET MVC5網(wǎng)站開發(fā)修改及刪除文章(十)
- ASP.NET MVC5網(wǎng)站開發(fā)文章管理架構(gòu)(七)
- ASP.NET MVC5網(wǎng)站開發(fā)用戶修改資料和密碼(六)
- ASP.NET?MVC5網(wǎng)站開發(fā)用戶登錄、注銷(五)
- ASP.NET?MVC5?網(wǎng)站開發(fā)框架模型、數(shù)據(jù)存儲(chǔ)、業(yè)務(wù)邏輯(三)
- ASP.NET?MVC5網(wǎng)站開發(fā)項(xiàng)目框架(二)
- ASP.NET MVC5網(wǎng)站開發(fā)概述(一)
- MVC4制作網(wǎng)站教程第二章 用戶修改資料2.4
相關(guān)文章
ASP.NET MVC實(shí)現(xiàn)批量文件上傳
這篇文章主要為大家詳細(xì)介紹了ASP.NET MVC實(shí)現(xiàn)批量文件上傳,簡(jiǎn)單介紹單文件上傳的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
.Net6集成IdentityServer4?+AspNetCore?Identity讀取數(shù)據(jù)表用戶且鑒權(quán)授權(quán)管理A
這篇文章主要介紹了.Net6集成IdentityServer4與AspNetCore?Identity讀取數(shù)據(jù)表用戶且鑒權(quán)授權(quán)管理API,IdentityServer4?實(shí)現(xiàn)鑒權(quán)、授權(quán),AspNetCore?Identity實(shí)現(xiàn)數(shù)據(jù)庫用戶管理表直接生成,下文詳情需要朋友可以參考一下2022-07-07
asp.net Linq把數(shù)據(jù)導(dǎo)出到Excel的代碼
最近有需要通過WEB把數(shù)據(jù)導(dǎo)出到Excel的功能, 關(guān)于導(dǎo)出數(shù)據(jù)到Excel并無什么新奇可言,網(wǎng)絡(luò)上到處都是,但基本上都是一種模式,通過DataGrid 把數(shù)據(jù)導(dǎo)出到Excel的方式。2008-10-10
asp.net 截取Http請(qǐng)求的實(shí)現(xiàn)代碼
本篇文章比較短,主要是因?yàn)槲业囊粋€(gè)隨想產(chǎn)生的一段代碼。 這段代碼的功能你可以叫做是簡(jiǎn)單的Http服務(wù)器也可以叫做Http請(qǐng)求截取。它實(shí)現(xiàn)的功能就是截取Http請(qǐng)求然后自己做處理。2010-06-06
IE下document.referrer 拒絕訪問的解決方法
原理就是給IE瀏覽器的頁面偷偷加了個(gè)鏈接,然后自動(dòng)點(diǎn)這個(gè)鏈接,于是referrer就能保留了,感興趣的朋友可以參考下2013-09-09
ASP.NET Core 集成 React SPA應(yīng)用的步驟
這篇文章主要介紹了ASP.NET Core 集成 React SPA應(yīng)用的步驟,幫助大家更好的理解和學(xué)習(xí)使用.net技術(shù),感興趣的朋友可以了解下2021-04-04
.net core 6.0 通過依賴注入注冊(cè)和使用上下文服務(wù)的教程
在.NET Core 6.0 中,獲取上下文的方式取決于您使用的技術(shù)棧和具體的應(yīng)用程序類型,這篇文章主要介紹了.net core 6.0 通過依賴注入注冊(cè)和使用上下文服務(wù)的教程,需要的朋友可以參考下2023-12-12
asp.net 數(shù)據(jù)綁定 使用eval 時(shí)候報(bào) 字符文本中的字符太多 問題的解決方法
asp.net 數(shù)據(jù)綁定 使用eval 時(shí)候報(bào) 字符文本中的字符太多 問題解決,需要的朋友可以參考下。2010-09-09

