【问题标题】:ActionLink route values containing specific characters包含特定字符的 ActionLink 路由值
【发布时间】:2015-01-08 11:54:45
【问题描述】:

我正在使用此操作链接将路由值 id 发送到控制器,但我的 id 值像这样 config.xml 这是我的操作链接

 @Html.ActionLink("Destroy", "DeleteFile", "Files", new { id = "config.xml"})

问题是当我想点击此链接时,浏览器将其理解为以config.xml 结尾的url

喜欢这个

http://localhost:12380/Files/DeleteFile/config.xml

并且不去控制器它返回404 - not found。 如何防止这种情况发生,并将这个config.xml作为参数而不是文件?

这也是我的路线

routes.MapRoute(
              name: "delete files",
              url: "Files/DeleteFile/{id}",
              defaults: new
              {
                  controller = "Files",
                  action = "DeleteFile",
                  id= UrlParameter.Optional
              }
            );

我也尝试了id ,filename,但没有任何改变

这是我的控制器

[HttpGet]
        public ActionResult DeleteFile(string id)
        {
          return view("DeleteFile");
         }

【问题讨论】:

  • 这是我的操作结果 [HttpGet] public ActionResult DeleteFile(string id) { return view("DeleteFile"); }
  • 你的路线怎么样?也许有一个“int”约束?
  • 这是我的路由 routes.MapRoute( name: "delete files", url: "Files/DeleteFile/{id}", defaults: new { controller = "Files", action = "DeleteFile" , id= UrlParameter.Optional } );

标签: c# razor actionlink routevalues


【解决方案1】:

您可以像这样使用this overload of Html.ActionLink() 来做到这一点:

@Html.ActionLink("Destroy", 
                "DeleteFile", 
                "Files", 
                new RouteValueDictionary { {"file", Url.Encode("config.xml")} }, 
                null)

和行动:

public ActionResult DeleteFile(string file)
{
  // delete logic here
  return View();
}

来自MSDN

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    RouteValueDictionary routeValues,
    IDictionary<string, Object> htmlAttributes
)

Here is a working DEMO Fiddle

【讨论】:

  • @Younisbarznji 不要使用id 作为参数使用其他名称,例如我使用的file,id 由路由更改,因此它被视为文件路径
  • 重点是当我从参数中删除 .xml 时,它工作正常,但 .xml 就像页面一样理解
  • 我也试过了,我改成 strFileName 但还是一样
  • @Younisbarznji:生成了什么链接?它应该像 http://localhost:12380/Files/DeleteFile?file=config.xml 那样应该可以工作......
  • 链接是localhost:12380/Files/DeleteFile/config.xml 它的工作方式是这样的 ?file="config.xml" 但我想在不使用这样的 url 的情况下实现它 ?file="config.xml"
【解决方案2】:

在这里我找到了答案,我们可以简单地在config.xml 末尾添加/

here is some answers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2012-09-23
    • 1970-01-01
    • 2013-11-17
    相关资源
    最近更新 更多