无法通过IRouter更改目标控制器/操作

时间:2018-12-18 20:07:38

标签: asp.net-core routing routes asp.net-core-mvc asp.net-core-2.1

我有简单的MyRouter:

public class MyRouter : IRouter
{
    private readonly IRouteBuilder _routeBuilder;

    public MyRouter(IRouteBuilder routeBuilder)
    {
        _routeBuilder = routeBuilder;
    }

    public async Task RouteAsync(RouteContext context)
    {
        if (ShouldReroute(...))
        {
            SetNeededPath(context, reroute);
        }

        await GetDefaultRouter().RouteAsync(context);
    }

    private bool ShouldReroute(...)
    {
        return true;
    }

    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        return GetDefaultRouter().GetVirtualPath(context);
    }

    private IRouter GetDefaultRouter()
    {
        return _routeBuilder.DefaultHandler;
    }

    private void SetNeededPath(RouteContext context, Reroute reroute)
    {
        context.RouteData.Values.Clear();

        context.RouteData.Values["action"] = "StoreContacts";
        context.RouteData.Values["controller"] = "Information";
    }
}

如您所见,它将请求的目的地更改为:

[Route("")]
public class InformationController : Controller
{
    [Route("StoreContacts")]
    public IActionResult StoreContacts()
    {
        return View();
    }
}

Startup.cs中的路由器描述为:

        app.UseMvc(routes =>
        {
           routes.MapRoute(
                name: "areas",
                template: "{area:exists}/{controller=Home}/{action=Index}");

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

            routes.Routes.Add(new MyRouter(routes));
        });

因此,在我的大脑中,它应该将所有未映射的请求重定向,例如 mysite.com/unexistingRoute 应该转到InformationController.StoreContacts,但我只有404。

mysite.com/StoreContacts 也可以通过直接URL访问。

1 个答案:

答案 0 :(得分:1)

属性路由将取代常规路由,因此您可以删除属性路由:

public class InformationController : Controller
{

    public IActionResult StoreContacts()
    {
        return View();
    }
}

然后通过IRouter将逻辑移到自定义路由。 mysite.com/unexistingRoute不会映射到Startup.cs中现有的路由模板配置。因此remove属性应该在您的方案中起作用。要映射其他网址,例如mysite.com/OtherAction,可以编写自定义逻辑,例如:

if (context.HttpContext.Request.Path.Value.StartsWith("/StoreContacts"))
{
        context.RouteData.Values["controller"] = "Information";
        context.RouteData.Values["action"] = "StoreContacts";
}