在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
首先新建项目看下main方法: public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } 其中,UseStartup<Startup>()方法使用了Startup类,在Startup类,有ConfigureServices和Configure方法,调用顺序是先ConfigureServices后Configure。
下面生成自定义的Service: public interface IMService { string GetString(); } public class MService:IMService { public string GetString() { return "这是我的服务"; } } 可以在ConfigureServices中这样使用: services.AddSingleton<IMService, MService>(); 或者 public static class MServiceExtensions { public static void AddMService( this IServiceCollection services) { services.AddScoped<IMService,MService>(); } } 这样就可以在ConfigureServices中这样用:services.AddMService();
下面自定义一个middleware
public class MMiddleware { private RequestDelegate nextMiddleware; public MMiddleware(RequestDelegate next) { this.nextMiddleware = next; } public async Task Invoke(HttpContext context) { context.Items.Add("middlewareID", "ID of your middleware"); await this.nextMiddleware.Invoke(context); } } 同样的,可以在Configure方法中这样使用:app.UseMiddleware<MMiddleware>(); 也可以 public static class MyMiddlewareExtensions { public static IApplicationBuilder UseMMiddleware (this IApplicationBuilder app) { return app.UseMiddleware<MMiddleware>(); } } 就可以app.UseMMiddleware(); public IActionResult Index() { ViewBag.str= service.Getstring(); ViewBag.MiddlewareID = HttpContext.Items["middlewareID"]; return View(); }
|
请发表评论