且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.Net Core中的动态路由

更新时间:2023-02-15 13:00:10

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

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()
    {
        //
    }
}