のために私はルートに特定のファイルが存在するときは常に特定のコントローラ/アクションメソッドへのすべての要求を私のASP.NET MVCのコアサイトをしたいと思います。アイデアは、私は特定の空のファイルを作成することにより、、必要に応じて「サイトメンテナンスのためダウン」のページを表示することができるということです。カスタムルータはメンテナンス
いくつかのカスタムミドルウェアを書きで遊んでたら、それは私がこれを行うカスタムIRouter
を作成することができなければならないことを私に夜が明けました。特定のファイルが存在する場合は、すべてのルート要求を「保守」ルートにマップする必要があります。しかし、私はそれを働かせることはできません。ここで
は、カスタムルータの定義です:
public class OfflineRouteHandler : IRouter
{
private readonly string _path;
private readonly IPAddress _remote;
public OfflineRouteHandler(string offlinePath, string remoteIP)
{
_path = offlinePath;
_remote = IPAddress.Parse(remoteIP);
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
// this returns a value...but RouteAsync is never called
StringBuilder path = new StringBuilder();
if(context.AmbientValues.ContainsKey("controller"))
path.Append(context.AmbientValues["controller"]);
if(context.AmbientValues.ContainsKey("action"))
{
if(path.Length > 0) path.Append("/");
path.Append(context.AmbientValues["action"]);
}
return new VirtualPathData(this, "/" + path.ToString());
}
public async Task RouteAsync(RouteContext context)
{
bool authorized = (context.HttpContext.Connection.RemoteIpAddress == _remote);
if(File.Exists(_path) && authorized)
{
// just for testing... but the method never gets called
var i = 9;
i++;
}
context.IsHandled = true;
}
}
次のように私はStartup.csでConfigure()
でそれを呼び出す:
string offlinePath = Path.Combine(Directory.GetParent(env.WebRootPath).FullName, "offline.txt");
app.UseMvc(routes =>
{
routes.Routes.Add(new TemplateRoute(new OfflineRouteHandler(offlinePath, "50.3.3.2"), "home/offline", new DefaultInlineConstraintResolver(routeOptions)));
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
routeOptions
がConfigure();
への呼び出しに渡されますどんな助けでも大歓迎です!
タイトルにタグを入れないで、適切なタグを使用してください! – Tseng