我不确定以下方法是否正确。它对我有用,但您应该针对您的场景进行测试。
首先创建一个用户服务来检查用户名:
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()
{
//
}
}