NET Core-學習筆記(四)

神牛003發表於2016-07-26

經過前面分享的三篇netcore心得再加上本篇分享的知識,netcore大部分常用知識應該差不多了,接下來將不會按照章節整合一起分享,因為涉及到的東西整合到一起篇幅太大了,所以後面分享將會按照某一個知識點分解,還請各位勿噴;本章要分享的資訊如下:

. Partial Views使用的簡單例子

. 注入服務到View中

. Controller輸出資料方法和Filters Attribute的貼圖

. IOptions<T>注入自定義讀取的配置檔案資料資訊服務

 

下面一步一個腳印的來分享:

. Partial Views使用的簡單例子

首先,這個區域性檢視Partial Views在實際專案中用途很多很廣,其實這個和前面mvc版本的用法差不多,這裡簡單舉例怎麼傳遞引數和非同步佈局的用法;咋們先在Shared資料夾中建立一個檢視名稱為_ShowListLi.cshtml,然後刪除裡面的所有程式碼(也就是變成空白的模板),再簡單在裡面寫入程式碼:

1 <li>@Model</li>
View Code

挺簡單的哈哈@Model對應的就是傳遞過來的引數,然後咋們建立個Controller對應返回一些列表資料這裡我使用前面章節現成的ArticlesController對應的程式碼:

 1 public async Task<IActionResult> Index( int id = 1)
 2         {
 3 
 4             var artiles = _context.Article;
 5             var pageOption = new MoPagerOption
 6             {
 7                 CurrentPage = id,
 8                 PageSize = 2,
 9                 Total = await artiles.CountAsync(),
10                 RouteUrl = "/Articles/Index"
11             };
12 
13             //分頁引數
14             ViewBag.PagerOption = pageOption;
15 
16             ViewBag.Plugin = _plugins.Value;
17 
18             //資料
19             return View(await artiles.OrderByDescending(b => b.CreateTime).Skip((pageOption.CurrentPage - 1) * pageOption.PageSize).Take(pageOption.PageSize).ToListAsync());
20         }
View Code

可以不用關心上面的這個Controller程式碼,因為是前面已經講過的,然後在對應的View中寫入如下程式碼:

1 <ul>
2     @foreach (var item in Model)
3     {
4         @await Html.PartialAsync("_ShowListLi", item.Title)
5     }
6 </ul>
View Code

執行的效果展示出了對應Title的資料如圖:

PartialAsync是一種呼叫區域性佈局試圖的方法,兩個引數,第一個是區域性試圖檔案的名稱這裡是_ShowListLi,第二個引數是要傳遞給引入的區域性試圖的引數這裡我使用列表資料中的Title;因為這是個非同步方法前面按照慣例需要await修飾程式碼就是這些,需要注意的是第一個引數如果區域性試圖檔案是在專案中的不同資料夾中引用的路徑不相同,這裡給出一段官網的程式碼加上翻譯的文字說明(不要太在意譯文的準確性):

//使用當前對應資料夾中名稱為ViewName檔案的佈局試圖
//如果同級資料夾中不存在ViewName那麼去專案中的Shared資料夾中查詢佈局檢視
@Html.Partial("ViewName")

//如果是完整的佈局檢視名稱加字尾如:ViewName.cshtml"),那麼只能查詢使用佈局檢視檔案所在的對應資料夾中是否存在本試圖
@Html.Partial("ViewName.cshtml")

//從專案根目錄查詢佈局檢視
@Html.Partial("~/Views/Folder/ViewName.cshtml")
@Html.Partial("/Views/Folder/ViewName.cshtml")

//使用相對路徑查詢試圖檔案
@Html.Partial("../Account/LoginPartial.cshtml")

 

. 注入服務到View中

首先,咋們定義一個服務類PublicClass和一個擷取字串方法_SubStrByLen,如下程式碼:

 1  public class PublicClass
 2     {
 3 
 4         public string _SubStrByLen(string org, int len = 50, string endStr = "...")
 5         {
 6 
 7             try
 8             {
 9                 if (string.IsNullOrEmpty(org)) { return org; }
10 
11                 //var gb = System.Text.Encoding.UTF8.GetBytes(org);
12                 //var tLen = gb.Length;
13 
14                 org = org.Trim();
15                 var tLen = org.Length;
16                 return tLen > len ? (org.Substring(0, len) + endStr) : org;
17             }
18             catch (Exception ex)
19             {
20 
21                 throw new Exception(ex.Message);
22             }
23         }
24     }
View Code

然後,在檔案Startup.cs中的ConfigureServices方法中使用AddTransient新增註入:

1 //注入依賴
2             services.AddTransient<Extend.PublicClass>();
View Code

此時注入完成,然後在試圖中使用,這裡咋們在上面建立的區域性試圖_ShowListLi.cshtml檔案中使用如下程式碼:

1 @inject Text.Core.Extend.PublicClass PTool
2 
3 <li>@Model</li>
4 <li>@PTool._SubStrByLen(Model,10,".....")</li>
View Code

試圖中使用@inject引入被注入的服務(引入的格式如:@inject <type> <name>),然後使用_SubStrByLen來擷取咋們的資料長度,效果如下圖:

咋們再繼續增加一個靜態方法來對比下,方法和上面截圖字串的服務是一樣的,如程式碼:

 1 public class PublicClassStatic
 2     {
 3 
 4         public static string _SubStrByLen(string org, int len = 50, string endStr = "...")
 5         {
 6 
 7             try
 8             {
 9                 if (string.IsNullOrEmpty(org)) { return org; }
10 
11                 //var gb = System.Text.Encoding.UTF8.GetBytes(org);
12                 //var tLen = gb.Length;
13 
14                 org = org.Trim();
15                 var tLen = org.Length;
16                 return tLen > len ? (org.Substring(0, len) + endStr) : org;
17             }
18             catch (Exception ex)
19             {
20 
21                 throw new Exception(ex.Message);
22             }
23         }
24 
25     }
View Code

因為是靜態方法,所以可以直接在試圖中使用如:

咋們再來看下執行的效果:

可以看出效果是一樣的,就寫程式碼速度上來將後者更快些,當然注入服務的方式在頁面使用也不無道理因為不可能所有的服務方法都弄成靜態的吧,這裡的列子只是簡單的擷取字串的效果

 

. Controller輸出資料方法和Filters Attribute的貼圖

這點主要是截圖Controller裡面Action對應的返回資料的方法:

對應的官網地址:https://docs.asp.net/en/latest/mvc/controllers/actions.html

Filters Attribute的貼圖:

對應官網地址:https://docs.asp.net/en/latest/mvc/controllers/filters.html

這兩個知識點會在後面的不斷擴充套件,歡迎繼續關注

 

. IOptions<T>注入自定義讀取的配置檔案資料資訊服務

首先,咋們建立一個配置檔案Plugin.json,內容資料如:

{
  "Plugins": [

    {
      "Plugin": {

        "Module": "API",
        "Des": "this is API"
      }
    },
    {
      "Plugin": {

        "Module": "MVC",
        "Des": "this is MVC"
      }
    }
  ]
}
View Code

再建立一個對應資料格式的實體類:

 public class Plugin
    {

        public string Module { get; set; }
        public string Des { get; set; }
    }
View Code

好咋們來讀取這個配置檔案資訊到實體物件中,還記得前面幾篇有講到怎麼獲取配置檔案資料麼,這裡我們使用ConfigurationBuilder讀取配置檔案,因為起始檔案Startup.cs檔案中有載入配置檔案的操作,所以我們直接在它的建構函式這裡新增載入我們剛剛新增的配置檔案如下程式碼:

1 var builder = new ConfigurationBuilder()
2 
3                 //env.ContentRootPath:獲取當前專案的跟路徑
4                 .SetBasePath(env.ContentRootPath)
5                 //使用AddJsonFile方法把專案中的appsettings.json配置檔案載入進來,後面的reloadOnChange顧名思義就是檔案如果改動就重新載入
6                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
7                 //這裡關注的是$"{param}"的這種寫法,有點類似於string.Format()
8                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
9                 .AddJsonFile("Plugin.json", optional: true, reloadOnChange: true);
View Code

是的使用AddJsonFile方法直接新增我們要讀取的配置檔名稱,這樣在例項物件ConfigurationBuilder呼叫Build()方法之後配置檔案就載入到程式中了,再賦值給了屬性Configuration,此屬性在方法ConfigureServices()可以直接使用,因為配置檔案中是一個陣列json所以轉到程式中是集合物件,所以有了如下程式碼:

 foreach (var item in Configuration.GetSection("Plugins").GetChildren())
                {

                    var plugin = new Plugin();

                    plugin.Module = item.GetSection("Plugin:Module").Value;
                    plugin.Des = item.GetSection("Plugin:Des").Value;
                   
                }
View Code

這裡迴圈中每次建立了Plugin物件並賦值了,但是沒有集合來儲存這些物件資料,這裡就要講到用IOptions<T>注入這些資料到Controller中去,注入關鍵程式碼:

 1 services.AddOptions();
 2 
 3             //初始化引數資訊
 4             services.Configure<List<Plugin>>(b =>
 5             {
 6 
 7                 foreach (var item in Configuration.GetSection("Plugins").GetChildren())
 8                 {
 9 
10                     var plugin = new Plugin();
11 
12                     plugin.Module = item.GetSection("Plugin:Module").Value;
13                     plugin.Des = item.GetSection("Plugin:Des").Value;
14                     b.Add(plugin);
15                 }
16             });
View Code

仔細看下這裡注入的資料型別是List<Plugin>,這樣就匹配配置檔案對應的json陣列了;

然後咋們去Controller中程式碼如圖:

然後通過_plugins.Value這樣就能得到注入進來的配置檔案資料了,咋們再通過ViewBag.Plugin = _plugins.Value儲存資料展示到試圖中程式碼如:

<table class="table">

    <tbody>
        @foreach (var item in ViewBag.Plugin as List<Plugin>)
        {
            <tr>
                <td>
                    @item.Module
                </td>
                <td>
                    @item.Des
                </td>
            </tr>
        }
    </tbody>
</table>
View Code

dotnet run能看到如下截圖效果:

這樣就完成了讀取自定義配置檔案到程式中,然後通過注入就可以在Controller使用了

這次的分享怎麼樣,望勿噴,後面分享的文章可能就專注某個知識點,不會一篇講太分散的知識了,希望各位朋友多多支援,謝謝。

 

 

相關文章