Core中的动态路由

Core中的动态路由

本文介绍了ASP.Net Core中的动态路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提供一种路由机制,其中路由是在运行时从用户帐户创建中生成的.例如http://mysite/username/home.

I need to provide a routing mechanic where the routes are generated at runtime from user account creations. Such as http://mysite/username/home.

我认为可以通过路由完成此操作,但是我不确定从何处开始使用ASP.Net Core.我在网上看到了一些有关MVC 5的示例,但ASP.Net Core似乎在处理路由方面略有不同.如何确保网站在http://mysite/username/news是用户自定义登录页面和http://mysite/news是网站新闻页面之间不会混淆?

I assume this can be done via routing but i'm not sure where to get started on it with ASP.Net Core. I've seen some examples online for MVC 5 but ASP.Net Core seems to handle routing a little bit differently. How can I ensure that the site doesn't get confused between http://mysite/username/news being the users custom landing page and http://mysite/news being the sites news page?

推荐答案

我不确定以下方法是否正确.它对我有用,但您应该针对自己的情况进行测试.

I am not sure if the below way is correct. It works for me but you should test it for your scenarios.

首先创建一个用户服务来检查用户名:

First create a user service to check username:

public interface IUserService
{
    bool IsExists(string value);
}

public class UserService : IUserService
{
    public bool IsExists(string value)
    {
        // your implementation
    }
}
// register it
services.AddScoped<IUserService, UserService>();

然后为用户名创建路由约束:

Then create route constraint for username:

public class UserNameRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        // check nulls
        object value;
        if (values.TryGetValue(routeKey, out value) && value != null)
        {
            var userService = httpContext.RequestServices.GetService<IUserService>();
            return userService.IsExists(Convert.ToString(value));
        }

        return false;
    }
}

// service configuration
services.Configure<RouteOptions>(options =>
            options.ConstraintMap.Add("username", typeof(UserNameRouteConstraint)));

最后编写路由和控制器:

Finally write route and controllers:

app.UseMvc(routes =>
{
    routes.MapRoute("default",
        "{controller}/{action}/{id?}",
        new { controller = "Home", action = "Index" },
        new { controller = @"^(?!User).*$" }// exclude user controller
    );

    routes.MapRoute("user",
        "{username:username}/{action=Index}",
        new { controller = "User" },
        new { controller = @"User" }// only work user controller
     );
});

public class UserController : Controller
{
    public IActionResult Index()
    {
        //
    }
    public IActionResult News()
    {
        //
    }
}

public class NewsController : Controller
{
    public IActionResult Index()
    {
        //
    }
}

这篇关于ASP.Net Core中的动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:47