溶液1通過使用操作篩選
Action filters
public class SampleActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
var myController = ((MyController)context.Controller);
context.Result = myController.RedirectToAction("SomeAction", "SomeController");
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
只需注意,方法RedirectToAction()是myController的類的一部分。通過使用IRouter
class MyRouter : IRouter
{
private readonly IRouter _defaulRouter;
public MyRouter(IRouter defaulRouter)
{
_defaulRouter = defaulRouter;
}
public async Task RouteAsync(RouteContext context)
{
// Set controller and action based on context.HttpContext.Request url
context.RouteData.Values["controller"] = "Home";
context.RouteData.Values["action"] = "About";
await _defaulRouter.RouteAsync(context);
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return _defaulRouter.GetVirtualPath(context);
}
}
啓動(Controller類已經有了這種方法,但它保護)
不要忘記註冊它Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(SampleActionFilter));
});
}
解決方案2 。配置
app.UseMvc(routes =>
{
routes.Routes.Add(new MyRouter(routes.DefaultHandler));
});
您可以使用路由約束,即IRouteConstraint接口嗎?在這裏找到博客文章:https://tommyb.com/customizing-asp-net-cores-route-constraints-and-model-binding/ – Jack