You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core MVC中完成搜索后更新URL路由?

解决ASP.NET Core MVC搜索后更新URL路由的问题

问题说明

在开发ASP.NET Core MVC应用时,执行搜索操作并返回Info视图展示数据后,URL仍停留在https://localhost:7236/Ingredient/Search,期望更新为包含搜索关键词和ID的格式,例如https://localhost:7236/Ingredient/Search/番茄/1。

解决方案步骤

1. 配置自定义路由

在Program.cs中添加匹配搜索结果的自定义路由规则,确保URL能正确解析参数:

var builder = WebApplication.CreateBuilder(args);

// 添加MVC服务
builder.Services.AddControllersWithViews();

var app = builder.Build();

// 配置中间件
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

// 添加自定义搜索路由
app.MapControllerRoute(
    name: "searchIngredient",
    pattern: "Ingredient/Search/{q}/{id}",
    defaults: new { controller = "Ingredient", action = "SearchDetails" }
);

// 默认路由
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}"
);

app.Run();

2. 修改控制器逻辑

移除原Search方法中的冗余参数,找到匹配结果后通过重定向更新URL,新增SearchDetails方法处理带参数的请求并返回Info视图:

// 处理初始搜索请求
public IActionResult Search(string search)
{
    // 直接查询匹配的食材(添加Trim避免空格问题)
    var result = _db.ingredients.FirstOrDefault(i => i.Name.Trim().Equals(search.Trim(), StringComparison.OrdinalIgnoreCase));
    
    if (result != null)
    {
        // 重定向到自定义路由,传递关键词和ID
        return RedirectToRoute("searchIngredient", new { q = result.Name, id = result.Id });
    }
    else
    {
        return NotFound();
    }
}

// 处理带参数的搜索结果请求,返回Info视图
public IActionResult SearchDetails(string q, int id)
{
    var ingredient = _db.ingredients.FirstOrDefault(i => i.Id == id && i.Name.Equals(q, StringComparison.OrdinalIgnoreCase));
    
    if (ingredient == null)
    {
        return NotFound();
    }
    
    return View("Info", ingredient);
}

3. 优化搜索表单(可选)

为表单添加method="get"确保搜索参数以GET方式传递(更符合搜索场景):

<form asp-controller="Ingredient" asp-action="Search" method="get">
    <div class="input-group">
        <div class="input-group-prepend">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
        </div>
        <input class="search-input form-control" name="search" placeholder="Ingredient..." />
    </div>
    <hr />
    <div class="btn-group">
        <button type="submit" class="btn btn-primary">Search</button>
        <a asp-controller="Ingredient" asp-action="List" class="btn btn-outline-primary">View List</a>
    </div>
</form>

关键说明

  • 直接返回View("Info", obj)属于服务器端视图渲染,不会触发浏览器跳转,因此URL不会改变;必须使用RedirectToRoute或RedirectToAction发起重定向,让浏览器请求新的URL。
  • 自定义路由的pattern可按需调整,比如改为Ingredient/Search?q={q}&id={id}的查询字符串格式,只需修改路由规则和重定向参数即可。

内容的提问来源于stack exchange,提问作者Jimmie Davis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:15:53