gpt4 book ai didi

c# - 为什么在 Controller 上下文之外获取路由值如此困难?

转载 作者:行者123 更新时间:2023-11-30 20:48:16 31 4
gpt4 key购买 nike

我不明白这背后的原因,为什么在 Controller 的 Request 中获取路由值如此容易,但在 HttpContext.Current 上几乎不可能做同样的事情。请求?

也许我只是不知道更好的方法,但它确实存在。有人可以确认这是从 Controller 外部获取路由数据的唯一方法吗?

例子

[Route("{id}"), HttpGet]
public IHttpActionResult Test()
{
// Simple and easy
var route1 = Request.GetRouteData().Values["id"];

// Wat. This is also ~6 times slower
var routeValues = (IHttpRouteData[]) HttpContext.Current.Request.RequestContext.RouteData.Values["MS_SubRoutes"];
var route2 = routeValues.SelectMany(x => x.Values).Where(x => x.Key == "id").Select(x => x.Value).FirstOrDefault();

return Ok(route1 == route2); // true
}

最佳答案

第一部分:

问题的答案——

Why is it so easy to get route values inside Request of controller but nearly impossible to do the same thing on HttpContext.Current.Request?

我不会详细介绍类实现和其他方面的所有细节。让我们考虑一下 MVC 架构中模型、 View 和 Controller 的职责。你可以看到只有 Controller 负责将路由映射到 View ,反之亦然。这是 MVC 架构中唯一需要路由的部分。因此很容易理解为什么在 Controller 中查找路由值如此容易。

现在是实现细节。是的,当然 MS 人员已经做了大量工作来使其在 Controller 内易于访问,只是一个简单的属性。但如果你想要它在 Controller 之外,你仍然可以拥有它,但这是一项艰苦的工作。这是相当大的,因为除非您试图搞乱架构的抽象层,否则无论如何您都不需要 Controller 外部的路由。

第二部分:

现在是第二个答案——

Can someone confirm that this is the only way to get route data outside controller?

当然还有其他方法。其实我自己也搞不明白,你这么辛苦干嘛要得到路由值?您不是在 Controller 中编写操作方法吗?如果是这样,那为什么不把它用作参数呢? -

[Route("{id}"), HttpGet]
public IHttpActionResult Test(int? id) //the easiest way to get route value for {id}
{
// Simple and easy
var route1 = Request.GetRouteData().Values["id"];

// Wat. This is also ~6 times slower
var routeValues = (IHttpRouteData[]) HttpContext.Current.Request.RequestContext.RouteData.Values["MS_SubRoutes"];
var route2 = routeValues.SelectMany(x => x.Values).Where(x => x.Key == "id").Select(x => x.Value).FirstOrDefault();

return Ok(route1 == route2 == id.Value); // true //should be true, and of course you should add null check since it is int? not int. But that is not significant here so I didn't do it.
}

关于c# - 为什么在 Controller 上下文之外获取路由值如此困难?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846869/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com