天天看點

NET Core-學習筆記(四)

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

. Partial Views使用的簡單例子

. 注入服務到View中

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

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

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

首先,這個局部視圖Partial Views在實際項目中用途很多很廣,其實這個和前面mvc版本的用法差不多,這裡簡單舉例怎麼傳遞參數和異步布局的用法;咋們先在Shared檔案夾中建立一個視圖名稱為_ShowListLi.cshtml,然後删除裡面的所有代碼(也就是變成空白的模闆),再簡單在裡面寫入代碼:

NET Core-學習筆記(四)
NET Core-學習筆記(四)

1 <li>@Model</li>      

View Code

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
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         }      

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
1 <ul>
2     @foreach (var item in Model)
3     {
4         @await Html.PartialAsync("_ShowListLi", item.Title)
5     }
6 </ul>      

運作的效果展示出了對應Title的資料如圖:

NET Core-學習筆記(四)

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")

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
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     }      

然後,在檔案Startup.cs中的ConfigureServices方法中使用AddTransient添加注入:

NET Core-學習筆記(四)
NET Core-學習筆記(四)
1 //注入依賴
2             services.AddTransient<Extend.PublicClass>();      

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
1 @inject Text.Core.Extend.PublicClass PTool
2 
3 <li>@Model</li>
4 <li>@PTool._SubStrByLen(Model,10,".....")</li>      

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

NET Core-學習筆記(四)

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
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     }      

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

NET Core-學習筆記(四)

咋們再來看下運作的效果:

NET Core-學習筆記(四)

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

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

NET Core-學習筆記(四)

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

Filters Attribute的貼圖:

NET Core-學習筆記(四)

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

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

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

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
{
  "Plugins": [

    {
      "Plugin": {

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

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

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
public class Plugin
    {

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

好咋們來讀取這個配置檔案資訊到實體對象中,還記得前面幾篇有講到怎麼擷取配置檔案資料麼,這裡我們使用ConfigurationBuilder讀取配置檔案,因為起始檔案Startup.cs檔案中有加載配置檔案的操作,是以我們直接在它的構造函數這裡添加加載我們剛剛添加的配置檔案如下代碼:

NET Core-學習筆記(四)
NET Core-學習筆記(四)
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);      

是的使用AddJsonFile方法直接添加我們要讀取的配置檔案名稱,這樣在執行個體對象ConfigurationBuilder調用Build()方法之後配置檔案就加載到程式中了,再指派給了屬性Configuration,此屬性在方法ConfigureServices()可以直接使用,因為配置檔案中是一個數組json是以轉到程式中是集合對象,是以有了如下代碼:

NET Core-學習筆記(四)
NET Core-學習筆記(四)
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;
                   
                }      

這裡循環中每次建立了Plugin對象并指派了,但是沒有集合來儲存這些對象資料,這裡就要講到用IOptions<T>注入這些資料到Controller中去,注入關鍵代碼:

NET Core-學習筆記(四)
NET Core-學習筆記(四)
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             });      

仔細看下這裡注入的資料類型是List<Plugin>,這樣就比對配置檔案對應的json數組了;

然後咋們去Controller中代碼如圖:

NET Core-學習筆記(四)

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

NET Core-學習筆記(四)
NET Core-學習筆記(四)
<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>      

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

NET Core-學習筆記(四)

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

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

git位址:

https://github.com/shenniubuxing3

    nuget釋出包:

https://www.nuget.org/profiles/shenniubuxing3
NET Core-學習筆記(四)