使用MVC /端点路由重写URL

时间:2019-11-07 00:35:18

标签: asp.net-core asp.net-core-mvc

我正在尝试将URL重写与MVC /端点路由结合使用。这是我的Startup.Configure方法的相关部分:

app.UseRewriter(new RewriteOptions().Add(new RewriteRuleTest()));

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

和RewriteRuleTest:

public class RewriteRuleTest : IRule
{
    public void ApplyRule(RewriteContext context)
    {
        HttpRequest request = context.HttpContext.Request;

        if (request.Path.Value.ToLower() == "/index")
        {
            request.Path = "/Home/Privacy";
            context.Result = RuleResult.SkipRemainingRules;
        }
    }
}

这似乎遵循建议,但是按/ index时得到404。我可以在上面的if语句中设置一个断点。我也可以直接导航到/ Home / Privacy,它可以正常工作。我已经尝试了RuleResult的所有三个选项。为什么重写不提供修改后的URL?

2 个答案:

答案 0 :(得分:1)

您还需要将网址重写器中间件放在app.UseRouting()之前:

app.UseRewriter(new RewriteOptions().Add(new RewriteRuleTest()));
app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

答案 1 :(得分:0)

您需要使用 DynamicRouteValueTransformer

app.UseEndpoints(endpoints =>
        {
            endpoints.MapDynamicControllerRoute<TranslationTransformer>("{language}/{controller}/{action}");
        });

public class TranslationTransformer : DynamicRouteValueTransformer
{
    private readonly TranslationDatabase _translationDatabase;

    public TranslationTransformer(TranslationDatabase translationDatabase)
    {
        _translationDatabase = translationDatabase;
    }

    public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
    {
        if (!values.ContainsKey("language") || !values.ContainsKey("controller") || !values.ContainsKey("action")) return values;

        var language = (string)values["language"];
        var controller = await _translationDatabase.Resolve(language, (string)values["controller"]);
        if (controller == null) return values;
        values["controller"] = controller;

        var action = await _translationDatabase.Resolve(language, (string)values["action"]);
        if (action == null) return values;
        values["action"] = action;

        return values;
    }
}

更多信息https://www.strathweb.com/2019/08/dynamic-controller-routing-in-asp-net-core-3-0/