都市网景,脱依服小游戏,盗情新浪共享
本文章主要说明asp.net core的创建和简单使用。
dotnet new web
dotnet new web -n baseWeb
,创建web项目,结果如下图所示:dotnet run
,即可运行此项目,此命令内部会执行dotnet build
命令编译项目,然后运行,结果如下:dotnet add package Microsoft.AspNet.Mvc
进行依赖包的安装public void ConfigureServices(IServiceCollection service){ service.AddMvc(); service.AddRouting(); }
上述添加此添加了Mvc,也添加了路由
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //添加的代码 app.UseMvc(routers=>{ routers.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); }
dotnet new page
实现的,但也可以使用手动创建。文件结果如下:dotnet run
运行,然后网页访问对就的地址即可aspnet core是自带了依赖注入功能的,就是StartUp类中ConfigureServices方法的IServiceCollection类型的形参。如果你想替换为autofac。请参考如下步骤
public IServiceProvider ConfigureServices(IServiceCollection service){ service.AddMvc(); service.AddRouting(); var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(service); containerBuilder.RegisterType<Services.ProductService>().As<Services.IProductService>(); var container = containerBuilder.Build(); return new AutofacServiceProvider(container); }
namespace baseWeb.Services { public interface IProductService { int Get(int id); } }
using System.Collections.Generic; namespace baseWeb.Services { public class ProductService:IProductService { List<int> ls = new List<int>(); public ProductService(){ for(var i=0; i<10; i++){ ls.Add(i+10); } } public int Get(int id){ return ls[id]; } } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace baseWeb.Controllers { public class HomeController:Controller { private Services.IProductService productService; public HomeController(Services.IProductService productService){ this.productService = productService; } public IActionResult Index(int id){ ViewData["value"] = this.productService.Get(id); return View(); } } }
在实际开发中,经常需要用到单元测试。.net core的单元测试也是如此的 so easy, fallow me。
dotnet new xunit -n baseWebTest
,即可创建一个以xunit为测试框架的单元测试项目dotnet add package Moq
,安装Moq模拟框架(此命令需要进入到baseWebTest项目文件夹后运行)dotnet add reference ../baseWeb/baseWeb.csproj
,将baseWeb项目引入到此项目中。using System; using Xunit; using Moq; using baseWeb.Controllers; using baseWeb.Services; using Microsoft.AspNetCore.Mvc; namespace basewebtest { public class DemoTest { [Fact] public void Test1() { var productServiceMock = new Mock<IProductService>(); productServiceMock.Setup(service=>service.Get(1)).Returns((int id)=>{ return id+10; }); var _controller = new HomeController(productServiceMock.Object); var result = _controller.Index(1); var objectResult = Assert.IsType<ViewResult>(result); var destResult = Assert.IsAssignableFrom<int>(objectResult.ViewData["value"]); Assert.Equal(11, destResult); } } }
dotnet test -p ./baseWebtest/baseWebtest.csproj
即可,看到如下结果:
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
asp.net搭建博客,使用BlogEngine.NET+MySql搭建博客
网友评论