zoukankan      html  css  js  c++  java
  • asp.net core 自定义中间件和service

    首先新建项目看下main方法:

    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();
    
        host.Run();
    }
    main方法

    其中,UseStartup<Startup>()方法使用了Startup类,在Startup类,有ConfigureServices和Configure方法,调用顺序是先ConfigureServices后Configure。

    下面生成自定义的Service:

    public interface IMService
    {
        string GetString();
    }
    
    public class MService:IMService
    {
        public string GetString()
        {
            return "这是我的服务";
        }
    }
    View Code

    可以在ConfigureServices中这样使用:

    services.AddSingleton<IMService, MService>();
    或者
    s
    ervices.AddScoped<IMService, MService>();
    或者
    services.AddTransient<IMService, MService>();
    这三个方法的作用都一样,只是生成实例的方式不一样,Singleton是所有的service都用单一的实例,Scoped 是一个请求一个实例,Transient 每次使用都是新实例。
    也可以使用依赖注入的方式添加服务
    public static class MServiceExtensions
    {
        public static void AddMService(
               this IServiceCollection services)
        {
            services.AddScoped<IMService,MService>();
        }
    }
    View Code

    这样就可以在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);
            }
        }
    View Code

    同样的,可以在Configure方法中这样使用:app.UseMiddleware<MMiddleware>();

    也可以

    public static class MyMiddlewareExtensions
    {
        public static IApplicationBuilder UseMMiddleware
                  (this IApplicationBuilder app)
        {
            return app.UseMiddleware<MMiddleware>();
        }
    }
    就可以app.UseMMiddleware();


    在controller中可以
    public IActionResult Index()
    {
        ViewBag.str= service.Getstring();
        ViewBag.MiddlewareID = HttpContext.Items["middlewareID"];
        return View();
    }





  • 相关阅读:
    10分钟学会React Context API
    Soft skill
    前端-页面性能调试:Hiper
    js对secure的支持是没问题的,httponly是为限制js而产生的,当然httponly的cookie也不会被js创建
    关于go的不爽
    Windows上mxnet实战深度学习:Neural Net
    wget获取https资源
    使用windows上 mxnet 预编译版本
    NVIDA 提到的 深度框架库
    Windows下编译mxnet
  • 原文地址:https://www.cnblogs.com/indexlang/p/5730056.html
Copyright © 2011-2022 走看看