MVC RouteConfig自定义maproute问题

时间:2015-12-16 23:17:04

标签: c# asp.net-mvc asp.net-routing maproute

我在routeConfig中有这个:

 routes.MapRouteLowercase(

                    name: "newProduct",

                    url: "{name}-{thisID}",


                    defaults: new

                    {

                        controller = "newProduct",

                        action = "Index",

                        name = UrlParameter.Optional


                    },
                     constraints: new { name = new MyProductConstraint() },
                    namespaces: new string[] { "khanoumiMetro.Controllers" }

                    );

这是MyProductConstraint代码:

  public class MyProductConstraint : IRouteConstraint
    {
        private KhanoumiDbContext db = new KhanoumiDbContext();


        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {

            if (values.ContainsKey(parameterName))
            {
                string url = values["name"].ToString();


                using (KhanoumiDbContext db = new KhanoumiDbContext())
                {
                    db.Database.Connection.Open();

                    return db.tbl_Product.Any(c => c.url==url);
                }

            }
            return false;
        }

    }

它有效,但如果我添加:

int id =(int)values [“thisID”];

并更改此行:

返回db.tbl_Product.Any(c => c.url == url);

要:

返回db.tbl_Product.Any(c => c.url == url&& c.ID == id);

我在应用程序运行时出现此错误: 指定的强制转换无效。

这里发生了什么?!

1 个答案:

答案 0 :(得分:1)

我已经改变了

int id =(int)values [" thisID"];

int id = Convert.ToInt32(values [" thisID"]。ToString());

还有routes.MapRouteLowercase到MapRoute并且问题解决了,我的问题是LowcaseRoutesMVC DLL,我必须向他们的开发人员报告。

相关问题