Tips:本篇已加入系列文章閱讀目錄,可點擊查看更多相關文章,
目錄
- 前言
- 開始
- 定義設定
- 使用設定
- 最后
前言
上一篇介紹了ABP模塊化開發的基本步驟,完成了一個簡單的檔案上傳功能,通常的模塊都有一些自己的配置資訊,比如上篇講到的FileOptions類,其中配置了檔案的上傳目錄,允許的檔案大小和允許的檔案型別,配置資訊可以通過Configuration(配置)和Options(選項)來完成,ABP還提供了另一種更靈活的方式: Settings(設定),本篇就來介紹一下ABP的設定管理,
開始
回顧一下上篇的FileOptions:

首先定義了一個FileOptions類,其中包含了幾個配置,然后在需要的地方中注入IOptions<FileOptions>就可以使用這些資訊了,
當然,模塊啟動時可以做一些配置修改,比如:

無論是組態檔還是這種代碼形式的配置,都是程式層面的修改;有些配置不太適合這樣做,比如這里的AllowedMaxFileSize和AllowedUploadFormats,它們應該在應用界面上,可以讓管理員自行修改,下面就來改造一下程式,
定義設定
使用設定之前需要先定義它,不同的模塊可以擁有不同的設定,
modules\file-management\src\Xhznl.FileManagement.Domain\Settings\FileManagementSettingDefinitionProvider.cs:
public class FileManagementSettingDefinitionProvider : SettingDefinitionProvider
{
public override void Define(ISettingDefinitionContext context)
{
/* Define module settings here.
* Use names from FileManagementSettings class.
*/
context.Add(new SettingDefinition(
FileManagementSettings.AllowedMaxFileSize,
"1024",
L("DisplayName:FileManagement.AllowedMaxFileSize"),
L("Description:FileManagement.AllowedMaxFileSize")
)
.WithProperty("Group1", "File")
.WithProperty("Group2", "Upload")
.WithProperty("Type", "number"),
new SettingDefinition(
FileManagementSettings.AllowedUploadFormats,
".jpg,.jpeg,.png,.gif,.txt",
L("DisplayName:FileManagement.AllowedUploadFormats"),
L("Description:FileManagement.AllowedUploadFormats")
)
.WithProperty("Group1", "File")
.WithProperty("Group2", "Upload")
.WithProperty("Type", "text")
);
}
private static LocalizableString L(string name)
{
return LocalizableString.Create<FileManagementResource>(name);
}
}
以上代碼定了了2個配置:AllowedMaxFileSize和AllowedUploadFormats,設定了它們的默認值、名稱和詳細說明,因為本專案使用了EasyAbp的SettingUi模塊,所以會有一些Group1,Group2之類的欄位,具體介紹可以參考Abp.SettingUi
使用設定
想讀取設定資訊,只需注入ISettingProvider即可,因為父類ApplicationService中已經注入,所以這里直接使用SettingProvider就好,獲取到配置,然后就可以做一些邏輯處理,比如判斷上傳檔案的大小和格式是否合法:
public class FileAppService : FileManagementAppService, IFileAppService
{
......
[Authorize]
public virtual async Task<string> CreateAsync(FileUploadInputDto input)
{
var allowedMaxFileSize = await SettingProvider.GetAsync<int>(FileManagementSettings.AllowedMaxFileSize);//kb
var allowedUploadFormats = (await SettingProvider.GetOrNullAsync(FileManagementSettings.AllowedUploadFormats))
?.Split(",", StringSplitOptions.RemoveEmptyEntries);
if (input.Bytes.Length > allowedMaxFileSize * 1024)
{
throw new UserFriendlyException(L["FileManagement.ExceedsTheMaximumSize", allowedMaxFileSize]);
}
if (allowedUploadFormats == null || !allowedUploadFormats.Contains(Path.GetExtension(input.Name)))
{
throw new UserFriendlyException(L["FileManagement.NotValidFormat"]);
}
......
}
}
前端設定界面:

下面可以隨便修改下設定,進行測驗:

最后
本篇內容較少,希望對你有幫助,代碼已上傳至 https://github.com/xiajingren/HelloAbp ,歡迎star,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/66458.html
標籤:.NET Core
上一篇:ASP.NET CORE 在類中如何使用SESSION
下一篇:C#資料庫存盤的檔案下載
