2

我在基于 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 );
}

虽然这可行,但我很想知道是否有更好的方法来做到这一点?

4

1 回答 1

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 方法的参数,但代价是必须编写自己的路由处理程序。

于 2012-05-04T15:30:55.257 回答