【问题标题】:Changing RouteData in Asp.Net Core 3.1 in Middleware在中间件中更改 Asp.Net Core 3.1 中的 RouteData
【发布时间】:2020-07-02 15:13:27
【问题描述】:

我最近将我的 .Net Core 2.1 应用程序更新到 3.1,但有一部分没有按预期升级。

我编写了代码来将子域映射到 here 所述的区域

我现在意识到使用app.UseMvc() 的方法应该替换为app.UseEndpoints(),但是我在3.1 框架中找不到任何地方可以让我在app.UseEndpoints() 之前写入RouteData

//update RouteData before this
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        "admin", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute(
        "default", "{controller=Home}/{action=Index}/{id?}");
});

有没有办法使用中间件写信给RouteData

我已尝试返回 app.UseMvc(),因为它仍在框架中,但 MvcRouteHandler 似乎不再存在

app.UseMvc(routes =>
{
    routes.DefaultHandler = new MvcRouteHandler(); //The type of namespace could not be found
    routes.MapRoute(
        "admin",
        "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(
        "default",
        "{controller=Home}/{action=Index}/{id?}");
});

【问题讨论】:

    标签: asp.net-core-3.1 asp.net-core-middleware


    【解决方案1】:

    尝试使用custom middleware

    添加使用Microsoft.AspNetCore.Routing的引用,使用Httpcontext.GetRouteData()方法实现RouteData

    app.UseRouting();
    
    app.Use(async (context, next) =>
    {
    
        string url = context.Request.Headers["HOST"];
        var splittedUrl = url.Split('.');
    
        if (splittedUrl != null && (splittedUrl.Length > 0 && splittedUrl[0] == "admin"))
        {
            context.GetRouteData().Values.Add("area", "Admin");
        }
    
        // Call the next delegate/middleware in the pipeline
        await next();
    });
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            "admin", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
        endpoints.MapControllerRoute(
            "default", "{controller=Home}/{action=Index}/{id?}");
    });
    

    【讨论】:

    • 太棒了,谢谢!我试图使用中间件,但我认为 GetRouteData() 只是一个吸气剂,并没有意识到你可以对它做 .Values.Add() 。
    • 注意顺序很重要!这个“app.Use”必须在“app.UseRouting”之后,但在“app.UseEndpoints”之前。此外,.NET Core 5 中的新功能:您还可以将其放入 context.Items["host"] = "foobar";不过,那不是 RouteData。
    猜你喜欢
    • 1970-01-01
    • 2020-09-23
    • 2018-02-19
    • 1970-01-01
    • 2021-01-29
    • 2020-05-20
    • 2021-08-31
    • 2016-11-25
    • 2021-07-16
    相关资源
    最近更新 更多