Dynamic routing in ASP.Net Core

痴心易碎 提交于 2019-12-05 01:57:52

问题


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

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?


回答1:


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


来源:https://stackoverflow.com/questions/38298312/dynamic-routing-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!