【问题标题】:.Net Core MVC RedirectToRoutePermanent does not redirect to matching action.Net Core MVC RedirectToRoutePermanent 不会重定向到匹配的操作
【发布时间】:2020-09-06 00:12:24
【问题描述】:

我正在做 .Net core mvc 项目,一个动作需要获取三个参数, 所以我首先在 Startup.cs

中创建了一条新路线
app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "partner_detail",
                    pattern: "Partners/Detail/{id}/{name}/{location}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}/{title?}");
            });

然后有一个表格,用户可以点击特定的合作伙伴,它会调用 partnercontroller

@Html.ActionLink(Model.Partner.Name, "Detail", "Partners", new { id = Model.Partner.Id, name = Model.Partner.Name, location = Model.Location }, new { @class = "anchor-1" })

我的动作方法如下,

[AllowAnonymous]
public IActionResult Detail(Guid id, string name, string location)
{
    string friendlyName = FriendlyUrlExtension.GetFriendlyTitle(name);
    string friendlyLocation = FriendlyUrlExtension.GetFriendlyTitle(location);

    if (!string.Equals(friendlyName, name, StringComparison.Ordinal) || !string.Equals(friendlyLocation, location, StringComparison.Ordinal))
    {
        return this.RedirectToRoutePermanent("partner_detail", new { id = id, name = friendlyName, location = friendlyLocation });
    }

    return View();
}

我正在将名称和位置转换为 SEO 友好名称并将其重定向到上述路线,

网址是格式化后的

https://myhost:00001/Partners/Detail/571ee251-b342-4fd3-b3df-0471ed54078e/partner-1/location-7

我有两个问题想请教各位专家

  1. 当我使用锚标记来调用操作时,它会在查询字符串中传递路由值,有没有办法将它们作为路由参数传递?
  2. 为什么 RedirectToRoutePermanent 没有触发我的操作?

有人可以帮我吗?

【问题讨论】:

    标签: asp.net-mvc redirect routes asp.net-core-mvc asp.net-mvc-routing


    【解决方案1】:

    好的, 我修好了它。 我使用.net核心锚标签助手如下,

    <a controller="Partners" asp-action="Detail" asp-route-id="@Model.Partner.Id" 
    asp-route-name="@Model.Partner.Name" asp-route-location="@Model.Location">@Model.Partner.Name</a>
    

    并从 startup.cs 中删除路由并作为属性添加到控制器操作中。

    [Route("Partners/Detail/{id}/{name}/{location}", Name = "partner_detail")]
    

    并且任何使用锚标记助手的人确保您的路由参数名称与路由属性中的参数相同。

    关于锚标签助手MSDN

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多