加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.Net Core中的动态路由

发布时间:2020-12-16 09:56:13 所属栏目:asp.Net 来源:网络整理
导读:我需要提供一个路由机制,其中路由是在运行时从用户帐户创建生成的.比如http:// mysite / username / home. 我认为这可以通过路由完成,但我不知道从哪里开始使用ASP.Net Core.我在网上看到了一些MVC 5的例子,但ASP.Net Core似乎处理的路由有点不同.如何确保
我需要提供一个路由机制,其中路由是在运行时从用户帐户创建生成的.比如http:// mysite / username / home.

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

解决方法

我不确定以下方式是否正确.它适用于我,但你应该为你的场景测试它.

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

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

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

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

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)));

最后写路由和控制器:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读