我在基于Django的Web应用程序中有一个URL,看起来与此类似:
/market/prices/2011-05-01/min/stocks/msft/dell/appl/
应用程序正在ASP.NET MVC 3中重写。我需要维护URL 。
问题的关键在于我支持由正斜杠分隔的多个股票代码符号。
我想要一个如下所示的自定义路线:
routes.MapRoute(
"Stocks",
"{queryDate}/{minOrMax}/stocks/{listOfStocksSeparatedByForwardSlash}",
new { controller = "Market", action = "Prices" }
);
控制器看起来像:
public ActionResult Prices(string queryDate, string minOrMax, ICollection<string> listOfStocksSeparatedByForwardSlash) {
var model = repository.List(queryDate, minOrMax, listOfStocksSeparatedByForwardSlash);
return View(model );
}
我目前的解决方案如下:
routes.MapRoute(
"Stocks",
"{queryDate}/{minOrMax}/stocks/{*listOfStocksSeparatedByForwardSlash}",
new { controller = "Market", action = "Prices" }
);
public ActionResult Prices(string queryDate, string minOrMax, string listOfStocksSeparatedByForwardSlash) {
var list = listOfStocksSeparatedByForwardSlash.Split('/').ToList();
var model = repository.List(queryDate, minOrMax, list);
return View(model );
}
虽然这有效,但我很想知道是否有更好的方法可以做到这一点?
答案 0 :(得分:0)
好的,这是一个选项,虽然我认为你的方法更容易。
您可以提供附加到路线的RouteHandler,如下所示:
routes.MapRoute(
name: "Test",
url: "Test/{someDate}/{*tickerSymbols}",
defaults: new { controller = "Home", action = "Test" }).RouteHandler = new SlashSeparatedTrailingParametersRouteHandler("tickerSymbols", "tickers");
路由处理程序为
public class SlashSeparatedTrailingParametersRouteHandler : IRouteHandler
{
private readonly string catchallParameterName;
private readonly string actionTargetParameter;
public SlashSeparatedTrailingParametersRouteHandler(string catchallParameterName, string actionTargetParameter)
{
this.catchallParameterName = catchallParameterName;
this.actionTargetParameter = actionTargetParameter;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (requestContext == null)
{
throw new ArgumentNullException("requestContext");
}
IRouteHandler handler = new MvcRouteHandler();
var vals = requestContext.RouteData.Values;
vals[this.actionTargetParameter] = vals[this.catchallParameterName].ToString().Split('/');
return handler.GetHttpHandler(requestContext);
}
}
如果这是您的控制器操作:
[HttpGet]
public ActionResult Test(DateTime someDate, string[] tickers)
{
if (tickers == null)
{
throw new ArgumentNullException("tickers");
}
return Content(string.Format("{0} and {1}", someDate, tickers.Length.ToString(CultureInfo.InvariantCulture)));
}
这是你的帖子:
http://localhost/Test/12-06-2012/Foo/Bar
然后你的输出是:
12/6/2012 12:00:00 AM and 2
在优雅方面,这会改进action方法的参数,但必须编写自己的路由处理程序。