加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 我们如何在ASP.NET Core中为我们的应用程序提供类似于架构

发布时间:2020-12-15 23:48:34 所属栏目:百科 来源:网络整理
导读:我想知道如何在我的应用程序中使用像asp.net core这样的中间件架构? 这个目标需要哪种模式? 是否有任何像这样的设计参考添加新功能和…? public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory){ loggerF
我想知道如何在我的应用程序中使用像asp.net core这样的中间件架构?

这个目标需要哪种模式?

是否有任何像这样的设计参考添加新功能和…?

public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseIdentity();

    // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",template: "{controller=Home}/{action=Index}/{id?}");
    });
}

使用非常简单的Configure方法,我们可以向应用程序添加新功能如何实现这样的功能?

解决方法

我要做的第一件事就是阅读 Middleware – Asp.Net Documentation

这将有助于了解中间件的使用方式以及实现自定义中间件所需遵循的实践.

直接取自docs

Middleware are software components that are assembled into an
application pipeline to handle requests and responses. Each component
chooses whether to pass the request on to the next component in the
pipeline,and can perform certain actions before and after the next
component is invoked in the pipeline. Request delegates are used to
build the request pipeline. The request delegates handle each HTTP
request.

现在,这表明它允许组件处理请求和响应.中间件按照添加到应用程序中间件集合的顺序执行.

app.UseStaticFiles();添加middlware来处理静态文件(图像,CSS,脚本等).

现在假设您希望在管道中添加自己的处理,您可以创建一个中间件类作为下面的示例.

public class GenericMiddleware
{
    public GenericMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    readonly RequestDelegate _next;

    public async Task Invoke(HttpContext context,IHostingEnvironment hostingEnviroment)
    {
        //do something

        await _next.Invoke(context);
    }
}

这里有一些有趣的点.首先,构造函数接受一个RequestDelegate,它本质上(但不完全是)将被调用的下一个中间件对象.

接下来,我们实现自己的Invoke方法.此方法应将HttpContext作为参数,并允许从IoC容器(在我的示例中为IHostingEnvironment实例)中注入其他依赖项.

然后,此方法执行它需要执行的代码,然后调用await _next.Invoke(context);执行RequestDelegate以调用下一个中间件类.

现在将其添加到应用程序中间件中,您只需调用即可

app.UseMiddleware< GenericMiddleware>();在startup.cs文件中的Configure(IApplicationBuilder app,ILoggerFactory loggerFactory)方法中.

或者创建一个简单的扩展方法.

public static class GenericMiddlewareExtensions
{
    public static IApplicationBuilder UseGenericMiddleware(this IApplicationBuilder app)
    {
        app.UseMiddleware<GenericMiddleware>();
        return app;
    }
}

然后将其称为app.UseGenericMiddleware();

现在,您实现自己的中间件的方式和原因取决于您.但是如上所述,由中间件调用下一个RequestDelegate,如果它没有,则它会停止请求.

以下是我的一个项目中的示例,该项目检查数据库是否已安装.如果它没有将请求重定向回安装页面.

public class InstallationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public InstallationMiddleware(RequestDelegate next,ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<InstallationMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        _logger.LogInformation("Handling request: " + context.Request.Path);
        if (context != null && !DatabaseHelper.IsDatabaseInstalled())
        {
            if (!context.Request.Path.ToString().ToLowerInvariant().StartsWith("/installation"))
            {
                context.Response.Redirect("/installation");
                return;
            }
        }

        await _next.Invoke(context);
        _logger.LogInformation("Finished handling request.");
    }
}

正如您所看到的!DatabaseHelper.IsDatabaseInstalled()我们重定向响应但不调用_next RequestDelegate.

文档再次说明了一切.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读