我可以读取我在MapControllerRoute中提供的匿名对象吗?在中间件类中。

huangapple go评论57阅读模式
英文:

Can I read the anonymous object which I supply in the MapControllerRoute in a middleware class"

问题

在我的.NET 6 MVC项目中,我有以下路由:

endpoints.MapControllerRoute(
    "Error",
    "error",
    new { controller = "Error", action = "Index", anonymousProperty = "3" });

在我的自定义中间件中,是否可以读取匿名对象(以及其中的anonymousProperty)?

我已经查看了RouteData中的context.GetRouteData();,但在那里没有显示出来。

英文:

in my .NET 6 MVC project I have this route:

endpoints.MapControllerRoute(
                    "Error",
                    "error",
                    new { controller = "Error", action = "Index", anonymousProperty ="3" });

Is it possible to read the anonymous object (and thereby the anonymousProperty) in my custom middleware?

I've looked in the RouteData context.GetRouteData(); but it doesn't show up there.

答案1

得分: 1

是的,但请确保如果您有明确的中间件,请将其放在UseRouting调用之后:

app.UseRouting();
app.Use(async (context, func) =>
{
    var routeValue = context.GetRouteValue("anonymousProperty"); // 3 for route .../error
    await func();
});
英文:

Yes, but be sure that your middleware is placed after UseRouting call if you have explicit one:

app.UseRouting();
app.Use(async (context, func) =>
{
    var routeValue = context.GetRouteValue("anonymousProperty"); // 3 for route .../error
    await func();
});

huangapple
  • 本文由 发表于 2023年2月8日 19:41:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定