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

ASP.NET MVC(C#)URL重写配置:自定义Story详情页URL

问题:ASP.NET MVC 实现故事详情页URL重写

我正在开发基于C#的ASP.NET MVC应用,需要修改故事详情页的URL。原有可正常访问的URL是:
Admin/Story/ViewDescription?storyId=1
希望改成View/{StoryID}的格式。我已经配置了路由规则和对应的Controller代码,请求指导正确的实现方案。

现有路由配置

routes.MapRoute(
    name: "ViewDescription",
    url: "View/{StoryID}",
    defaults: new { controller = "Story", action = "ViewDescription", StoryID = UrlParameter.Optional }
);

现有Controller代码

public ActionResult ViewDescription(int StoryID)
{
    if (StoryID <= 0)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Invalid Story ID");
    }

    List<AddStoryDTO> titleWithDescriptions = bll.Viewdescription(StoryID);
    List<ReviewDTO> reviews = bll.GetReviews(StoryID);

    if (titleWithDescriptions != null && titleWithDescriptions.Count > 0)
    {
        ViewBag.Reviews = reviews; 
        return View(titleWithDescriptions);
    }
    else
    {
        return HttpNotFound("No descriptions found for the provided Story ID.");
    }
}

正确实现方案

  • 调整路由优先级:ASP.NET MVC路由按从上到下的顺序匹配,必须把这个自定义路由放在默认路由之前,否则默认路由会先拦截请求,导致自定义规则不生效。修改后的路由顺序示例:

    // 自定义路由放在最前面
    routes.MapRoute(
        name: "ViewDescription",
        url: "View/{StoryID}",
        defaults: new { controller = "Story", action = "ViewDescription" }
    );
    
    // 默认路由放在后面
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    
  • 移除可选参数标记:Controller方法中StoryID是必填的int类型,不能设置为UrlParameter.Optional,否则当URL不带ID时(如View/)会抛出参数绑定异常,直接删除这个配置项即可。

  • 参数名称保持一致:当前路由中的StoryID和Controller方法参数名已经匹配,这部分无需修改,但后续调整时要确保名称完全一致(虽然默认不区分大小写,但统一命名更规范)。

  • 测试URL兼容性:

    • 新URL View/1 应能正常访问,正确调用Story控制器的ViewDescription方法并传入ID。
    • 旧URL Admin/Story/ViewDescription?storyId=1 会继续生效(只要默认路由存在),如果要禁用旧URL,可添加路由过滤或权限限制。
  • 生成正确的页面链接:在视图中生成新格式的URL时,要指定路由名称来确保链接正确:

    // 使用RouteLink生成超链接
    @Html.RouteLink("查看故事详情", "ViewDescription", new { StoryID = 1 })
    
    // 或者生成纯URL字符串
    @Url.RouteUrl("ViewDescription", new { StoryID = 1 })
    

内容的提问来源于stack exchange,提问作者Aahana Dutta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:59:55