vs code 中开发 .net5 mvc
asp.net core mvc
------------
安装vscode-solution-explorer,C# 2个扩展。遇到yes就点yes。
新建一个文件夹:D:\repos\Net5Mvc
用vscode打开这个文件夹
在vscode终端中输入
创建解决方案文件
dotnet new sln -n Net5Mvc
遇到yes就点yes。
创建Web项目
dotnet new web -n Net5MvcWeb
将项目添加到解决方案中
dotnet sln add Net5MvcWeb
修改Properties文件夹中的 launchSettings.json文件:
找到Net5MvcWeb节点,将applicationUrl修改为:http://localhost:5001
"Net5MvcWeb": { "commandName": "Project", "dotnetRunMessages": "true", "launchBrowser": true, "applicationUrl": "http://localhost:5001;https://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }
按F5 debug起来
如果遇到:
You don't have an extension for debugging C#. Should we find a C# extension in the Marketplace?
双击Startup.cs文件,过会儿会有个提示,点击YES。
默认页面显示:Hello World!
改成MVC页面:
修改Startup.cs-ConfigureServices,增加一行:services.AddControllersWithViews();
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); }
修改Configure方法中的app.UseEndpoints
替换为:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); // app.UseEndpoints(endpoints => // { // endpoints.MapGet("/", async context => // { // await context.Response.WriteAsync("Hello World!"); // }); // }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
在Net5MvcWeb项目中新建Controllers文件夹
在Controllers文件夹中新建HomeController.cs文件,回车后选择class
using Microsoft.AspNetCore.Mvc;
类继承: Controller
加入Index Action:
using System; using Microsoft.AspNetCore.Mvc; namespace Net5MvcWeb.Controllers { public class HomeController: Controller { public IActionResult Index() { return Content("Hello 11"); } } }
发布的话, 在vscode-solution-explorer中右键Net5MvcWeb,选择publish。
输出位置:D:\repos\Net5Mvc\Net5MvcWeb\bin\Debug\net5.0\publish\
可以复制并部署到IIS了。
默认是:dotnet "publish" "d:\repos\Net5Mvc\Net5MvcWeb\Net5MvcWeb.csproj" 命令,可能不符合发布需要。可以百度:dotnet "publish"命令。
Release发布,输出目录:d:/temp/Net5MvcWebR,--self-contained false 依赖框架:
dotnet publish -c Release -r win-x64 -o d:/temp/Net5MvcWebR --self-contained false
参照了:https://ken.io/note/asp.net-core-tutorial-mvc-quickstart