我使用的是这样的路由:
routes.MapRoute("Invoice-New-NewCustomer",
"Invoice/New/Customer/New/{*name}",
new { controller = "Customer", action = "NewInvoice" },
new { name = @"[^\.]*" });有一个处理此路由的操作:
public ActionResult NewInvoice(string name)
{
AddClientSideValidation();
CustomerViewData viewData = GetNewViewData();
viewData.InvoiceId = "0";
viewData.Customer.Name = name;
return View("New", viewData);
}当我调用return RedirectToAction("NewInvoice", "Customer", new {name});并且name等于"The C# Guy“时,"name”参数被截断为"The C“。
所以我的问题是:用ASP.NET MVC处理这种特殊字符的最好方法是什么?
谢谢!
发布于 2008-12-31 19:07:36
好吧,不幸的是,我确认这是ASP.NET路由中的一个已知问题。问题在于,在路由的内部,我们在转义Uri的路由参数时使用Uri.EscapeString。但是,该方法不会转义"#“字符。
请注意,从技术上讲,#字符(也称为Octothorpe)是错误的字符。这种语言实际上是一个"C“,后面跟着一个锐号,就像在音乐中一样:http://en.wikipedia.org/wiki/Sharp_(music)♯
如果你使用了锐号,就有可能解决这个问题。:P
另一个解决方案是,因为大多数人都想使用octothorpe,就是为该路由编写一个自定义路由,并在获得虚拟路径路径后,使用将#编码为%23的HttpUtility.UrlEncode对#符号进行编码。
作为后续,我想向您指出这篇博客文章,其中谈到了如何传入其他“无效”字符。http://haacked.com/archive/2010/04/29/allowing-reserved-filenames-in-URLs.aspx
发布于 2008-12-17 04:16:07
URL编码!更改链接,使其对特殊字符进行编码。
Server.URLencode(strURL)C#将变为"c%23“。
发布于 2008-12-17 19:23:53
在我的机器上工作。下面是我用来创建最简单示例的方法。
//Global.asax.cs
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication4 {
public class MvcApplication : System.Web.HttpApplication {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute("Invoice-New-NewCustomer",
"Invoice/New/Customer/New/{*name}",
new { controller = "Customer", action = "NewInvoice" },
new { name = @"[^\.]*" });
}
protected void Application_Start() {
RegisterRoutes(RouteTable.Routes);
}
}
}
//HomeController.cs
using System.Web.Mvc;
namespace MvcApplication4.Controllers {
[HandleError]
public class HomeController : Controller {
public ActionResult Index() {
return RedirectToAction("NewInvoice", "Customer", new { name = "The C# Guy" });
}
}
}
//CustomerController.cs
using System.Web.Mvc;
namespace MvcApplication4.Controllers {
public class CustomerController : Controller {
public string NewInvoice(string name) {
return name;
}
}
}然后,我启动了我的应用程序并导航到/home/index。发生了THe重定向,我在浏览器中看到了"The C# Guy“。
https://stackoverflow.com/questions/373599
复制相似问题