2008-12-17 44 views
15

我使用类似的路线这一个:如何传递特殊字符,以便ASP.NET MVC可以正确处理查询字符串数据?

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});和名称等于“C#的人”时, “name”参数被截断为“The C”。

所以我的问题是:ASP.NET MVC处理这种特殊字符的最佳方法是什么?

谢谢!

回答

16

好的,我确认这是现在不幸的是,ASP.NET路由中的一个已知问题。问题是,在路由的深处,我们使用Uri.EscapeString为Uri转义路由参数。但是,该方法不会转义“#”字符。

请注意#字符(aka Octothorpe)在技术上是错误的字符。 C♯语言实际上是一个“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

3

URL编码!更改链接以便编码特殊字符。

Server.URLencode(strURL) 

C#将变成“c%23”。

3

适用于我的机器。以下是我所做的创建最简单的示例。

//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 C#Guy”。

+0

是它重定向到 发票/新建/客户/新建/本+ C%2523 +盖伊 或 客户/ NewInvoice?名称=在%2BC%2523%2BGuy ? – labilbe 2008-12-18 04:00:31

+0

啊,我明白了。我会研究它。 – Haacked 2008-12-19 19:02:13

相关问题