來份ASP.NET Core嘗嘗


0x01、前言

學習ASP.NET Core也有一段時間了,雖說很多內容知識點還是處於一知半解的狀態,但是基本的,還是

略懂一二。如果有錯誤,還望見諒。

本文還是和之前一樣,Demo+在Linux下運行(CentOS7+dotnetcore sdk)

開發環境:win10+vs2015+sqlserver2014

 

0x02、demo

新建一個ASP.NET Core Web Application項目--Catcher.EasyDemo.Website

干掉Controllers文件夾。由於個人習慣問題,習慣性將Controller分離出來。

新建三個Class Library項目:

Catcher.EasyDemo.Controllers:剝離出來的Controller

Catcher.EasyDemo.DataAccess:數據訪問

Catcher.EasyDemo.Models:模型

Controller項目需要添加MVC的引用:"Microsoft.AspNetCore.Mvc": "1.0.0"

在Controllers中添加HomeController,內容和生成的是一樣的。然后在Website中添加引用,這里有

兩種方式,一種是和平常一樣的右鍵->添加引用,另一種是在project.json中的dependencies節點下

面添加 "Catcher.EasyDemo.Controllers": "1.0.0-*",然后就會自動restore,完成之后就能正常跑起

來了。(這里就不截圖了)

下面的話,在Models中添加一個Product類:

 1 namespace Catcher.EasyDemo.Models
 2 {
 3     public class Product
 4     {
 5         public int ProductId { get; set; }
 6         public string ProductName { get; set; }
 7         public string ProductSource { get; set; }
 8         public decimal ProductPrice { get; set; }
 9     }
10 }

在DataAccess中添加ProductDataAccess類,用於數據交互,里面有用到dapper,所以要添加引用,

以及用到了讀取json配置的方法,所以還要添加Microsoft.Extensions.Configuration的引用,同時還要添加Models的引用,方法上面已經說過了。

這里沒有用一些復雜的東西,就一個單例模式和一些簡單的數據庫操作。

  1 using Catcher.EasyDemo.Models;
  2 using Dapper;
  3 using Microsoft.Extensions.Configuration;
  4 using System.Collections.Generic;
  5 using System.Data;
  6 using System.Data.SqlClient;
  7 using System.IO;
  8 using System.Linq;
  9 
 10 namespace Catcher.EasyDemo.DataAccess
 11 {
 12     public sealed class ProductDataAccess
 13     {
 14         public static ProductDataAccess Instance
 15         {
 16             get
 17             {
 18                 return Nested.instance;
 19             }
 20         }
 21 
 22         class Nested
 23         {
 24             static Nested() { }
 25             internal static readonly ProductDataAccess instance = new ProductDataAccess();
 26         }
 27 
 28         /// <summary>
 29         /// get the connection string form the appsettings.json
 30         /// </summary>
 31         /// <returns></returns>
 32         private string GetConnStr()
 33         {
 34             var builder = new ConfigurationBuilder();
 35             builder.SetBasePath(Directory.GetCurrentDirectory());
 36             builder.AddJsonFile("appsettings.json");
 37             var config = builder.Build();             
 38             return config.GetConnectionString("dapperConn");
 39         }
 40                
 41         /// <summary>
 42         /// open the connection
 43         /// </summary>
 44         /// <returns></returns>
 45         private SqlConnection OpenConnection()
 46         {
 47             SqlConnection conn = new SqlConnection(GetConnStr());
 48             conn.Open();
 49             return conn;
 50         }
 51 
 52         /// <summary>
 53         /// get all products
 54         /// </summary>
 55         /// <returns></returns>
 56         public IList<Product> GetAll()
 57         {
 58             using (IDbConnection conn = OpenConnection())
 59             {
 60                 string sql = @"SELECT [ProductId]
 61                                   ,[ProductName]
 62                                   ,[ProductSource]
 63                                   ,[ProductPrice]
 64                               FROM [dbo].[Product]";
 65                 return conn.Query<Product>(sql).ToList();
 66             }
 67         }
 68 
 69         /// <summary>
 70         /// delete the product by product's id
 71         /// </summary>
 72         /// <param name="pid">id of the product</param>
 73         /// <returns></returns>
 74         public bool Delete(int pid)
 75         {           
 76             using (IDbConnection conn = OpenConnection())
 77             {
 78                 string sql = string.Format(@"DELETE FROM [dbo].[Product] WHERE [ProductId]={0} ", pid.ToString());
 79                 return conn.Execute(sql) > 0;
 80             }
 81         }
 82 
 83         /// <summary>
 84         /// add the product
 85         /// </summary>
 86         /// <param name="product">entity of the product</param>
 87         /// <returns></returns>
 88         public bool Add(Product product)
 89         {
 90             using (IDbConnection conn = OpenConnection())
 91             {
 92                 string sql = string.Format(@"INSERT INTO [dbo].[Product]
 93            ([ProductName]
 94            ,[ProductSource]
 95            ,[ProductPrice])
 96      VALUES
 97            ('{0}','{1}',{2})", product.ProductName, product.ProductSource, product.ProductPrice);
 98                 return conn.Execute(sql) > 0;
 99             }
100         }
101     }
102 }
然后在Controllers中添加一個ProductController,具體內容如下:
 
 1 using Microsoft.AspNetCore.Mvc;
 2 using Catcher.EasyDemo.Models;
 3 using Catcher.EasyDemo.DataAccess;
 4 
 5 namespace Catcher.EasyDemo.Controllers
 6 {
 7     public class ProductController :  Controller
 8     {
 9         /// <summary>
10         /// Index
11         /// </summary>
12         /// <returns></returns>        
13         public IActionResult Index()
14         {           
15             return View(ProductDataAccess.Instance.GetAll());
16         }
17 
18         /// <summary>
19         /// Add
20         /// </summary>
21         /// <returns></returns>
22         public IActionResult Add()
23         {
24             return View();
25         }
26         [HttpPost]
27         public IActionResult Add(Product product)
28         {
29             bool isOK = ProductDataAccess.Instance.Add(product);
30 
31             if (isOK)
32             {
33                 return RedirectToAction("Index");
34             }
35             else
36             {
37                 TempData["err"] = "sorry!there were some errors!Please try again.";
38                 return View();
39             }
40         }
41 
42         /// <summary>
43         /// Delete
44         /// </summary>
45         /// <param name="pid"></param>
46         /// <returns></returns>
47         public IActionResult Delete(int pid)
48         {
49             bool isOK = ProductDataAccess.Instance.Delete(pid);
50 
51             if (isOK)
52             {
53                 return RedirectToAction("Index");
54             }
55             else
56             {
57                 TempData["err"] = "sorry!there were some errors!Please try again.";
58                 return View("Index");
59             }
60         }
61     }
62 }
 
控制器的話,應該沒有什么太多好說的,畢竟差別不會太大。
 
下面要做的就是添加視圖和連接字符串。
 
先添加視圖:添加一個Product文件夾,在這里存放相應的視圖

添加Index.cshtml

 1 @model IEnumerable<Catcher.EasyDemo.Models.Product>
 2 @{
 3     ViewData["Title"] = "Product Index";
 4 }
 5 <a asp-action="Add" asp-controller="Product">Add a New Product</a>
 6 <div class="container">
 7     <table class="table table-responsive">
 8 
 9         <thead>
10             <tr>
11                 <td>ID</td>
12                 <td>Name</td>
13                 <td>Price</td>
14                 <td>Source</td>
15                 <td>Opreation</td>
16             </tr>
17         </thead>
18 
19         <tbody>
20             @foreach (var item in Model)
21             {
22                 <tr>
23                     <td>@item.ProductId</td>
24                     <td>@item.ProductName</td>
25                     <td>@item.ProductPrice</td>
26                     <td>@item.ProductSource</td>
27                     <td>
28                         <a asp-action="Delete" asp-controller="Product" asp-route-pid="@item.ProductId">Delete</a>
29                     </td>
30                 </tr>
31             }
32         </tbody>
33     </table>
34 </div>

視圖與mvc用的法大致相同,不同就是TagHelper,不過大部分是一看就知道是什么意思,要做什么操作,也不做過多解釋。

添加Add.cshtml
 
 1 @model Catcher.EasyDemo.Models.Product
 2 @{
 3     ViewData["Title"] = "Add";
 4 }
 5 <div class="container">
 6     <form asp-action="Add" asp-controller="Product" method="post">
 7         <div class="form-group">
 8             <label asp-for="ProductName">Name</label>
 9             <input asp-for="ProductName" type="text" placeholder="enter the product name" />
10         </div>
11         <div class="form-group">
12             <label asp-for="ProductPrice">Price</label>
13             <input asp-for="ProductPrice" type="text" placeholder="enter the product price" />
14         </div>
15         <div class="form-group">
16             <label asp-for="ProductSource">Source</label>
17             <input asp-for="ProductSource" type="text" placeholder="enter the product source" />
18         </div>
19         <div class="form-group">
20             <button type="submit" class="btn btn-primary">Add Product</button>
21         </div>
22     </form>
23 </div>
 
還要添加的是連接字符串,在appsettings.json中添加一個節點
 
1 "connectionStrings": {
2     "dapperConn": "server=127.0.0.1;database=nancydemo;user id=sa;password=123;"
3   }

當然,這是在本地的,放到linux時,需要替換成相應的ip

來一張項目截圖:
 
 
到這里,編碼工作已經ok了,編譯,發布即可

0x03、Linux下運行

這里沒有采用jexus的方式部署,原因是想嘗嘗另外的方式。

在CentOS上安裝dotnet core的方式可以看這里,就不在累贅了

安裝好了之后,運行dotnet會提示

確定dotnet core 安裝成功之后,

就是把發布后的項目扔到CentOS中,習慣放到/var/www目錄下面

進入到相應的目錄,運行dotnet 網站對應的dll即可

 

並且,在終端還能查看一系列的操作
 
 

 

 總之,dotNET Core 用起來感覺不錯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM