使用MVC路由器确定路由是否存在
是否可以使用ASP.NET Core MVC路由器来确定重定向到特定位置是否成功?
Is it possible to use the ASP.NET Core MVC Router to determine, if a redirect to a specific location might be successfull?
我想注入MVC路由器,然后问一下,我要使用的路由是否存在,但是我正在努力寻找正确的注入类,并且在MVCRouter中看不到任何使用方法
I'd like to inject the MVC Router and just ask it, if the route I want to use exists at all, but I'm struggling finding the correct classes to inject and did not see any method of use in the MVCRouter.
我也可以覆盖默认路由器,并使用必要的方法对其进行扩展.
I would also be okay in overriding the default router and extend it with the neccessary methods.
一种方法是将IActionSelector
注入到您的组件中.
One way to do this would be to inject IActionSelector
to your component.
该组件负责控制器动作的选择,并且可以告诉您是否存在具有给定参数的路由(即使存在歧义匹配项).
That component is responsible for controller action selection, and can tell you if there is a route with given parameters (and even if there is an ambiguous match).
public class HomeController : Controller
{
private readonly IActionSelector _actionSelector;
public HomeController(IActionSelector actionSelector)
{
_actionSelector = actionSelector;
}
public IActionResult Index()
{
var routeData = new RouteData();
routeData.Values["action"] = "DoesNotExist";
routeData.Values["controller"] = "Home";
var routeContext = new RouteContext(HttpContext)
{
RouteData = routeData
};
IReadOnlyList<ActionDescriptor> candidates = _actionSelector.SelectCandidates(routeContext);
if (candidates == null || candidates.Count == 0)
{
//No actions matched
}
else
{
try
{
var actionDescriptor = _actionSelector.SelectBestCandidate(routeContext, candidates);
if(actionDescriptor == null)
{
//No action matched
}
//Action matched
}
catch (AmbiguousActionException)
{
//More than 1 action matched
}
}
return View();
}
}
本质上是MvcRouteHandler
所做的.首先找到所有可能的候选者,然后将其过滤为最佳候选者.如果发现一个以上的异常,可能会引发异常,您可能想要也可能不想处理.
It's essentially what MvcRouteHandler
does. First finds all the possible candidates, then filters that to the best candidate. It can throw an exception if it finds more than one, which you may or may not want to handle.
我想,是否可以通过扩展组件来更改行为来简化此操作,但是MvcRouteHandler
并不是那么容易扩展.当前,如果没有动作匹配,它只会记录一条消息,这不会影响返回值.而且我们真的不能在那里更改签名.
I thought if you could somehow do this easier by extending a component to change behaviour, but MvcRouteHandler
is not that easy to extend. It currently just logs a message if no action matches, which does not affect the return value. And we can't really change the signature there.