以下の方法が正しいかどうかはわかりません。それは私のために働くが、シナリオのためにそれをテストする必要があります。
まずユーザー名を確認するために、ユーザーサービスを作成します。
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()
{
//
}
}
あなたがこの問題を解決タクシー右にルーティングします。たとえば、[Route( "{username}/news")]のルートに[Route ["news"]の別のルートがあります。それは意味をなさないか、私は誤解していますか? –
あなたは '{username}'を使うことができないと思いました。 asp.netのコアは、アイデンティティを見てそれを処理するのですか? 'http:// mysite/johndoe/news'が公開URLであればどうなりますか?認証されていない人はそれを打つことができますか? –
申し訳ありませんが、あなたのルート上のパラメータとしてそれを持っていて、必要に応じてリダイレクトしています。意味がある? –