http://ASP.NET Core篇上一篇手把手教你寫dotnet core(入門篇)我們已經(jīng)簡單在dotnet core里面跑了個"hello world!"和累加程序.

今天我們的步子邁大一點,直接上 http://ASP.NET Cor" />

国产成人精品无码青草_亚洲国产美女精品久久久久∴_欧美人与鲁交大毛片免费_国产果冻豆传媒麻婆精东

15158846557 在線咨詢 在線咨詢
15158846557 在線咨詢
所在位置: 首頁 > 營銷資訊 > 網(wǎng)站運營 > 手把手教你ASP.NET Core

手把手教你ASP.NET Core

時間:2023-07-25 00:33:01 | 來源:網(wǎng)站運營

時間:2023-07-25 00:33:01 來源:網(wǎng)站運營

手把手教你ASP.NET Core:

http://ASP.NET Core篇

上一篇手把手教你寫dotnet core(入門篇)我們已經(jīng)簡單在dotnet core里面跑了個"hello world!"和累加程序.

今天我們的步子邁大一點,直接上 http://ASP.NET Core了

http://ASP.NET Core 是一個新的開源和跨平臺的框架,用于構(gòu)建如 Web 應(yīng)用、物聯(lián)網(wǎng)(IoT)應(yīng)用和移動后端應(yīng)用等連接到互聯(lián)網(wǎng)的基于云的現(xiàn)代應(yīng)用程序。http://ASP.NET Core 應(yīng)用可運行于 .NET Core 和完整的 .NET Framework 之上。 構(gòu)建它的目的是為那些部署在云端或者內(nèi)部運行(on-premises)的應(yīng)用提供一個優(yōu)化的開發(fā)框架。它由最小開銷的模塊化的組件構(gòu)成,因此在構(gòu)建你的解決方案的同時可以保持靈活性。你可以在 Windows、Mac 和 Linux 上跨平臺的開發(fā)和運行你的 http://ASP.NET Core 應(yīng)用。 http://ASP.NET Core 開源在 GitHub 上。






創(chuàng)建http://ASP.NET Core程序

開發(fā)環(huán)境: dotnet SDK + VS Code




這里還是直接使用dotnet new命令來創(chuàng)建http://ASP.NET Core項目, 終端中輸入"dotnet new web -n FirsrMVC".

自動創(chuàng)建FirsrMVC文件夾并生成對應(yīng)的csproj和CS文件,具體操作和輸出信息如下:




? codelover-blog git:(master) ? dotnet new web -n FirsrMVCThe template "ASP.NET Core Empty" was created successfully.This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.Processing post-creation actions...Running 'dotnet restore' on FirsrMVC/FirsrMVC.csproj... Restoring packages for /Users/liguobao/code/codelover-blog/FirsrMVC/FirsrMVC.csproj... Generating MSBuild file /Users/liguobao/code/codelover-blog/FirsrMVC/obj/FirsrMVC.csproj.nuget.g.props. Generating MSBuild file /Users/liguobao/code/codelover-blog/FirsrMVC/obj/FirsrMVC.csproj.nuget.g.targets. Restore completed in 1.97 sec for /Users/liguobao/code/codelover-blog/FirsrMVC/FirsrMVC.csproj.Restore succeeded.? codelover-blog git:(master) ? cd FirsrMVC? FirsrMVC git:(master) ? lsFirsrMVC.csproj Program.cs Startup.cs obj/ wwwroot/





Program.cs




在VS Code中打開FirsrMVC文件夾,簡單看一下文件和Program.cs的代碼







Program.cs依舊是Main主方法,然后調(diào)用了一下BuildWebHost方法,BuildWebHost返回一個IWebHost的實例,接著Run.

先不管這里具體做了什么事情,我們從語義上理解一下.

  1. BuildWebHost構(gòu)建一個Web的Host實例,然后把WebHost實例運行起來了
  2. 創(chuàng)建WebHost使用了一個Startup的類
  3. 關(guān)于詳細(xì)WebHost的詳細(xì)解析見:ASP.NET Core 運行原理解剖[1]:Hosting



Startup.cs




先直接上一波代碼




using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.DependencyInjection;namespace FirsrMVC{ public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //直接往HTTP Response中寫入"Hello World!",即在頁面直接顯示此字符 app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } }}


  1. ConfigureServices:運行時被調(diào)用,將服務(wù)(services)添加到容器(container)中
  2. Configure:運行時被調(diào)用, 配置HTTP request 的pipeline
嗯,看不懂?沒關(guān)系,待會一個個演示.

我們這里還是直接先跑一下程序,FirsrMVC文件夾路徑下執(zhí)行:dotnet run
輸出如下:




? FirsrMVC git:(master) ? dotnet runHosting environment: ProductionContent root path: /Users/liguobao/code/codelover-blog/FirsrMVCNow listening on: http://localhost:5000Application started. Press Ctrl+C to shut down.





然后訪問http://localhost:5000看看.







好了,第一個MVC程序已經(jīng)跑起來了,本文結(jié)束.逃...

這里應(yīng)該還有人吧?那我們繼續(xù)了.




wwwroot中的靜態(tài)文件




  1. 在wwwroot文件夾新增first.html,隨便寫個能看見的HTML標(biāo)簽(我寫的是p標(biāo)簽)
  2. 在 Configure 方法中添加一句 app.UseStaticFiles(); 然后再重新運行一下
  3. 訪問http://localhost:5000/first.html






本步驟完成.

UseStaticFiles()方法:調(diào)用一個讀取wwwroot文件夾下面的靜態(tài)文件輸出的中間件注冊到程序中,從而完成靜態(tài)文件的輸出.

這里也告訴我們,http://ASP.NET Core的靜態(tài)文件(JS+CSS+圖片...)之類的都可以放這邊來.

甚至于如果簡單做前后端分離的話,前端的vue/react項目都可以扔這里去.




重頭戲MVC




終于要講到MVC了.




MVC模式最早由Trygve Reenskaug在1978年提出[1],是施樂帕羅奧多研究中心(Xerox PARC)在20世紀(jì)80年代為程序語言Smalltalk發(fā)明的一種軟件架構(gòu)。MVC模式的目的是實現(xiàn)一種動態(tài)的程式設(shè)計,使后續(xù)對程序的修改和擴展簡化,并且使程序某一部分的重復(fù)利用成為可能。除此之外,此模式通過對復(fù)雜度的簡化,使程序結(jié)構(gòu)更加直觀。軟件系統(tǒng)通過對自身基本部分分離的同時也賦予了各個基本部分應(yīng)有的功能。






  1. 控制器(Controller)- 負(fù)責(zé)轉(zhuǎn)發(fā)請求,對請求進行處理。
  2. 視圖(View) - 界面設(shè)計人員進行圖形界面設(shè)計。
  3. 模型(Model) - 程序員編寫程序應(yīng)有的功能(實現(xiàn)算法等等)、數(shù)據(jù)庫專家進行數(shù)據(jù)管理和數(shù)據(jù)庫設(shè)計(可以實現(xiàn)具體的功能)。
以上概念來自維基百科:MVC

http://ASP.NET Core,MVC模型一般就對應(yīng)著三個文件夾,Models/Views/Controllers.

  1. Models:存放一些業(yè)務(wù)實體類,如Student,Course等,表現(xiàn)上就是C#的.cs文件
  2. Views:存放CSHTML文件,http://ASP.NET Core的模板文件,類HTML,也可以寫C#代碼
  3. Controllers: cs文件,繼承Controller類的XXXController,實現(xiàn)業(yè)務(wù)邏輯代碼







下面一起來寫一個簡單的MVC玩玩.




Startup




修改 Startup.cs的代碼,新增MVC中間件的引用,操作如下:

  1. Startup.cs中的ConfigureServices方法下新增:services.AddMvc();
  2. Configure方法下去掉之前的UseMvc,改成
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });





全部代碼如下:




using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;namespace FirsrMVC{ public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }}





Controllers




新增Controllers文件夾,在此文件下新建HomeController.cs文件,然后填入一下代碼:




using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;namespace FirsrMVC.Controllers{ public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { return Json(new { name = "我的名字", success = true }); } }}





到這里,我們先運行一下代碼.

如無意外的話,

訪問http://localhost:5000/ 空白一片,

訪問http://localhost:5000/Home/About 會輸出




{ "name": "我的名字", "success": true}





http://localhost:5000/




其實這里訪問的是http://localhost:5000/Home/Index,對應(yīng)方法是HomeController/Index

我們看一下Log輸出會發(fā)現(xiàn)這樣的一句錯誤"fail: The view 'Index' was not found. Searched locations: /Views/Home/Index.cshtml, /Views/Shared/Index.cshtml"

原因是HomeController中的Index返回的是View,

程序默認(rèn)就會去/Views/目錄下尋找/Home/Index.cshtml文件來渲染然后返回給瀏覽器,但是這里我們并沒有這個文件,所以直接GG.




http://localhost:5000/Home/About




對應(yīng)方法是HomeController/About,返回為Json數(shù)據(jù),不需要View.

所以直接就往瀏覽器輸出了{(lán) name = "我的名字", success = true }的Json格式數(shù)據(jù)




Views




上一步我們的的Controller已經(jīng)建好了,但是缺View文件,我們這里來創(chuàng)建一下View文件

新建Views/Home文件夾,然后再在此文件夾下新增Index.cshtml文件

然后在Index.cshtml中輸入:




<p>First View Page</p>>





刷新一下http://localhost:5000/頁面.







View文件也建立好了.




Models




最后簡單講一下Model.

同理,新建Models文件夾,在此文件夾下新增Student.cs文件.




namespace FirsrMVC{ public class Student { public string Name { get; set; } public int Age { get; set; } }}





我們想做的要做的是把Student信息通過Controller返回給View,然后用View渲染出來.

修改一下HomeController/Index方法:




public IActionResult Index() { Student student = new Student() { Name = "小明", Age = 16 }; return View(student); }





修改一下Views/Home/Index.cshtml




@model FirsrMVC.Student@if(Model !=null){ <p>@Model.Name<span>今年</span>@Model.Age<span></span></p>}else{ <p>這里什么都沒有.</p>}





重新運行一下程序,訪問http://localhost:5000/







MVC結(jié)束.

本文完.

預(yù)告:下一節(jié)配置文件+DI依賴注入.

關(guān)鍵詞:把手

74
73
25
news

版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。

為了最佳展示效果,本站不支持IE9及以下版本的瀏覽器,建議您使用谷歌Chrome瀏覽器。 點擊下載Chrome瀏覽器
關(guān)閉