如何为此网址路由创建约束?

时间:2011-05-02 20:53:28

标签: c# asp.net regex url-routing

   routes.MapPageRoute("View Home Page",
        "{homepage}",
        "~/home.aspx",
        true,
        new RouteValueDictionary { { "homepage", "national" } },
        new RouteValueDictionary { { "region", "^(national|bc|ab|on){0,1}$" } }
       );

我只希望路线与http://www.mydomain.com/nationalhttp://www.mydomain.com/bchttp://www.mydomain.com/abhttp://www.mydomain.com/on

等网址相匹配

如何构建约束?

2 个答案:

答案 0 :(得分:2)

我最终写了一个自定义约束,所以我的代码现在看起来像这样:

routes.MapPageRoute("View Home Page",
        "{region}/default.aspx",
        "~/home.aspx",
        true,
        new RouteValueDictionary { { "region", "national" } },
        new RouteValueDictionary { { "region", new HomePageConstraint() } }
       );

和班级:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;

/// <summary>
/// Summary description for HomePageConstraint
/// </summary>
public class HomePageConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return GetRegions().Any(x => x.ToLower() == values[parameterName].ToString().ToLower());

    }


    private List<string> GetRegions()
    {
        List<string> set = new List<string>();
        set.Add("National");
        set.Add("BC");
        set.Add("AB");
        set.Add("SASK");
        set.Add("MAN");
        set.Add("ON");
        set.Add("QC");
        set.Add("Maritimes");
        set.Add("NL");

        return set;

    }
}

效果很好(我使用的是webforms而不是mvc - 我确信它在两个实例中都有效)。找到了这里的方法:http://stephenwalther.com/blog/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx

答案 1 :(得分:0)

还没有回复,所以我会告诉你我做了什么。不幸的是,ASP.NET MVC的路由引擎并不是最好的。

您需要更改相应的变量以匹配您的路由和视图,但这应该可以帮助您入门。

将此作为您正在映射的最后路线:

routes.MapRoute("Root", "{pathName}", new
{ 
    controller = "Root", 
    action = "Default"
});

在你的控制器中:

public class RootController : Controller
{

    [HttpGet]
    public ActionResult Default(string pathName)
    {
        // No pathName? 

        if (String.IsNullOrWhiteSpace(pathName)) {
            return this.View("~/Views/Root/home.aspx")
        }

        // Check to see if there's a view for the pathName

        var viewPath = String.Format("~/Views/Root/{0}.aspx", pathName);

        if (File.Exists(Server.MapPath(viewPath))) {
            return this.View(viewPath);
        }

        // Not found

        this.Response.StatusCode = System.Net.HttpStatusCode.NotFound;
        return this.View("~/Views/404.aspx");
    }

}

因此,您需要在您期望的“pathNames”之后命名您的观点:

  • 〜/查看/根/ national.aspx
  • 〜/查看/根/ ab.aspx
  • 〜/查看/根/ bc.aspx

如果你不介意这样的约定,那也不算太糟糕。