我想要这种机制:
我尝试修改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?}");
});
}
它仅适用于第二颗子弹。
我的代码出了什么问题?以及如何实现我的目标?
答案 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);
}
结论:
感谢您的帮助