如何重写.net核心中的URL?

时间:2018-02-28 21:37:03

标签: c# asp.net .net asp.net-core .net-core

我想要这种机制:

  • 当用户尝试访问 localhost / pro / details / alias =>显示此页面但有小网址 localhost / alias
  • 当用户尝试直接访问 localhost / alias =>显示此页面的相同网址 localhost / alias
  • 当用户尝试访问* localhost / {controller} / {action} / id =>像往常一样显示这个页面

我尝试修改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?}");
    });
}

它仅适用于第二颗子弹。

我的代码出了什么问题?以及如何实现我的目标?

2 个答案:

答案 0 :(得分:1)

你能尝试this方法吗?

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

答案 1 :(得分:1)

为了实现我的目标,我做了以下事情:

首先我修改我的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" });

        });

所以我创建了一条新路线 默认路线以便定位特殊行动:DetailsAlias(见下文)

我还修改了我的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);
    }

结论:

  • 如果我试图直接点击/ bob =&gt;显示具有相同网址的“Bob详情页面”
  • 如果我试图点击/专业/详情/ 1 =&gt;用/ bob Url
  • 显示'Bob Detail page'

感谢您的帮助