從零開始構建一個的asp.net Core 項目(一)


最近突發奇想,想從零開始構建一個Core的MVC項目,於是開始了構建過程。

首先我們添加一個空的CORE下的MVC項目,創建完成之后我們運行一下(Ctrl +F5)。我們會在頁面上看到“Hello World!”。

既然是從零開始構建的項目,我們需要搞明白這個“Hello World!”是從哪里出現的? 點開我們的項目,我們會看到VS為我們生成了兩個類,一個是Program.cs 和startup.cs,和一個空文件夾(wwwroot),除此之外VS在也沒有為我們多生成了任何東西。

我們首先從這兩個類開始分析,program.cs這個類是不是和console application的program.cs 有點像呢。我們點進去看一下

 1   public class Program
 2     {
 3         public static void Main(string[] args)
 4         {
 5             var host = new WebHostBuilder()
 6                 .UseKestrel()
 7                 .UseContentRoot(Directory.GetCurrentDirectory())
 8                 .UseIISIntegration()
 9                 .UseStartup<Startup>()
10                 .UseApplicationInsights()
11                 .Build();
12 
13             host.Run();
14         }
15     }
Program

我們看到有一個這里邊就有一個主函數,這里就是主程序的入口。開發過winfrom的人,應該心里都有印象了吧,在winfrom的開發過程中,我們的項目也有一個這樣的類,只不過里邊最后一行寫的是Application.run(),這里是host.run(),這樣程序就啟動了。我們也看到了 .UseStartup<Startup>()這么一行代碼,這里就是用的startup.cs的那個類。

我們打開startup.cs 這個類

 1  public class Startup
 2     {
 3 
 4         public void ConfigureServices(IServiceCollection services)
 5         {
 6         }
 7 
 8         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 9         {
10             loggerFactory.AddConsole();
11 
12             if (env.IsDevelopment())
13             {
14                 app.UseDeveloperExceptionPage();
15             }
16 
17             app.Run(async (context) =>
18             {
19                 await context.Response.WriteAsync("Hello World!");
20             });
21         }
22     }

在這里我找到了"Hello World!"的來源了。

於是我又想能不能讓它顯示一個界面,就像我們生成的MVC項目那樣,有個home的界面。

想實現那個效果我們一步一來。 首先我們的每一個View在conroll中對應一個action,這樣我們才可以訪問到我們的View ,當然在startup.cs中我們需要進行配置相應的服務,進行依賴注入。

那我先建了一個Views文件夾,和Controllers文件夾。在Views文件夾中添加兩個界面,一個是_ViewStrart.cshtml 和_ViewImports.cshtml從名字中可以看出他們對應得功能。一個是整個View的起點,另一個是整個view里邊添加的引用。

在Views文件夾下創建Share文件夾,共享的文件夾。就是每個View都用的。相當於母版頁吧。

這里為了和VS生成的MVC項目一樣我在Share文件下添加了一個_Layout.cshtml 文件(名稱可以隨便起)。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewData["Title"] - WebApplication1</title>
    <link href="~/site.css" rel="stylesheet" />
    <link href="~/bootstrap.css" rel="stylesheet" />
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">Test_NULL</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2017 - WebApplication1</p>
        </footer>
    </div>
</body>
</html>
<script src="~/jquery.js"></script>
<script src="~/bootstrap.js"></script>
_Layout.cshtml

我在里邊引用了Bootstrap.css和BootStrap.js ,juery.js 和site.css

這是site.css,其余三個都可以在相應的網站上下載。這幾個文件都在wwwroot文件下的根目錄中(這里為了簡化)

body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Wrapping element */
/* Set some basic padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Set widths on the form inputs since otherwise they're 100% wide */
input,
select,
textarea {
    max-width: 280px;
}

/* Carousel */
.carousel-caption p {
    font-size: 20px;
    line-height: 1.4;
}

/* Make .svg files in the carousel display properly in older browsers */
.carousel-inner .item img[src$=".svg"] {
    width: 100%;
}

/* Hide/rearrange for smaller screens */
@media screen and (max-width: 767px) {
    /* Hide captions */
    .carousel-caption {
        display: none;
    }
}
.myTextArea {
    width: 100% !important;
}
site.css

 

由於我使用了Razor語法和taghelper標簽,所以我們在這里需要添加相應的引用。

打開nuget包管理器找到下邊這兩個包,點擊安裝就可以了,當然了也可以打開*.csproj文件進行編輯

打開_ViewStrart.cshtml在里邊添加,這里說明一下,Layout = "~/Views/Shared/_Layout.cshtml";表示的是默認情況下所有VIew都是用的這個母版頁,當然了你也可以在界面中自己重新聲明

@{
     Layout = "~/Views/Shared/_Layout.cshtml";
}

打開_ViewImports.cshtml 在里邊添加(這里聲明了我所有的view中都可以用Taghelper),寫過自定義TagHelper的可能在這里比較明了。*是代表所有 逗號后邊表示的是程序集的名稱。

@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers

下邊我們在Views文件夾下添加一個Home文件夾在Home文件夾下添加一個Index.cshtml文件。(這里為了演示一切從簡)

@{
    ViewData["Title"] = "Index Page";
}
<h1>這是測試用的Index頁面</h1>

由於一個View對應Controller中的一個action,我們要在Controllers文件中添加一個HomeController.cs MVC控制器類(一切從簡)

using Microsoft.AspNetCore.Mvc;

namespace Test_Null.Controllers
{
    public class HomeController : Controller
    {
       
        public IActionResult Index()
        {
            return View();
        }
    }
}
HomeController.cs

這樣前台界面已經搭建完畢了就剩怎么調用了。

我回到了StartUp.cs 這個類

由於我們用的是MVC所以在這里我添加了MVC這個包的引用

在StartUp.cs 類里邊的這方法中配置這項服務

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

由於我在前台界面中用了js和css這樣的靜態文件(在wwwroot的根目錄中)所以在這里我要加上靜態包的引用。關於這個包的高級應用這里有篇博客

http://www.cnblogs.com/linezero/p/5541326.html

修改StartUp.cs 類

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();//使用靜態文件默認的文件夾為wwwroot

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{Controller=Home}/{action=Index}/{id?}"
                );
            });
        }

這是修改后的整個Startup.cs類和最開始做個對比

 1  public class Startup
 2     {
 3         public void ConfigureServices(IServiceCollection services)
 4         {
 5             services.AddMvc();
 6         }
 7         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 8         {
 9             loggerFactory.AddConsole();
10 
11             if (env.IsDevelopment())
12             {
13                 app.UseDeveloperExceptionPage();
14             }
15             app.UseStaticFiles();//使用靜態文件默認的文件夾為wwwroot
16 
17             app.UseMvc(routes =>
18             {
19                 routes.MapRoute(
20                     name: "default",
21                     template: "{Controller=Home}/{action=Index}/{id?}"
22                 );
23             });
24         }
25     }
Startup.cs

到這里就完成了。運行一下(Ctrl+F5)

運行結果

通過這個構建過程,讓我對每個包的用途有了點理解,以及MVC的運行過程。和依賴注入(DI),服務的配置有了點了解,本來想連上數據庫進行操作,可是我用EF的時候除了點問題,等問題解決了,再寫篇從零開始連上數據庫的演示。

 


免責聲明!

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



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