简体   繁体   English

如何在.net core中重写URL?

[英]How to rewrite URL in .net core?

I would like this mecanism: 我想要这种机制:

  • when user try to access to localhost/pro/details/alias => show this page but with tiny url localhost/alias 当用户尝试访问localhost / pro / details / alias =>时显示此页面,但URL很小localhost / alias
  • when user try to directly access to localhost/alias => show this page with same url localhost/alias 当用户尝试直接访问localhost / alias =>时,使用相同的url localhost / alias显示此页面
  • when user try to access to *localhost/{controller}/{action}/id => show this page as usual 当用户尝试访问* localhost / {controller} / {action} / id =>时,如常显示此页面

I tried to modify startup.cs 我试图修改startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    var rewrite = new RewriteOptions()
        .AddRewrite(@"([a-zA-Z0-9\-]*)", "pro/details/$1", skipRemainingRules: true);

    app.UseRewriter(rewrite);

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

It works only for the second bullet. 它仅适用于第二个项目符号。

What's wrong with my code? 我的代码有什么问题? And how to achieve my goal? 以及如何实现我的目标?

Could you try this approach? 您可以尝试这种方法吗?

 var rewrite = new RewriteOptions()
     .AddRewrite(@"(P|p)ro/(D|d)etails/(.*)", "$1", skipRemainingRules: true);

In order to achieve my goal, I did following stuff : 为了实现我的目标,我做了以下工作:

First I modify my startup.cs like : 首先,我将我的startup.cs修改为:

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "ProfessionnalAlias",
                template: "{id?}",
                defaults: new { controller = "Professionnals", action = "DetailsAlias" });

        });

So I created a new route, after default route in order to target special action : DetailsAlias (see below) 因此,我 默认路由 之后创建了一个新路由,以针对特殊操作:DetailsAlias(请参见下文)

And I also modify my ProfessionnalsController like : 而且我还像这样修改了ProfessionnalsController:

    /// <summary>
    /// This action have an Integer parameter and redirect to action with alias
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var professional = await _context.professional 
            .SingleOrDefaultAsync(m => m.id == id);
        if (professional == null)
        {
            return NotFound();
        }

        RedirectResult redirectResult = new RedirectResult("/"+professional.alias);

        return redirectResult;
    }

    /// <summary>
    /// This action show detail view from alias parameter
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<IActionResult> DetailsAlias(string id)
    {
        if (string.IsNullOrEmpty(id))
        {
            return NotFound();
        }

        var professional= await _context.professional.SingleOrDefaultAsync(m => m.alias == id);
        if (professional== null)
        {
            return NotFound();
        }

        return View("Details", professional);
    }

Conclusion : 结论:

  • If I tried to hit directly /bob => show 'Bob Detail page' with same URL 如果我尝试直接打/ bob =>显示具有相同网址的“鲍勃详细信息页面”
  • If I tried to hit /professional/Details/1 => show 'Bob Detail page' with /bob Url 如果我尝试按/ professional / Details / 1 =>使用/ bob Url显示“鲍勃详细信息页面”

Thanks for help 感谢帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM