C# 控制器过载指标法 目标
重载“Index”方法,使其类似于C# 控制器过载指标法 目标,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,重载“Index”方法,使其类似于myapp.com/Category/SomethingHere/ 问题 我有CategoryController和Index()方法,如下所示: // // GET: /Category/ public ActionResult Index(string categoryName) { if (categoryName != null) return View(categoryName); else {
myapp.com/Category/SomethingHere/
问题
我有CategoryController
和Index()
方法,如下所示:
//
// GET: /Category/
public ActionResult Index(string categoryName)
{
if (categoryName != null)
return View(categoryName);
else
{
return Content("Test");
}
}
在我访问myapp.com/Category/Cars/
或myapp.com/Category/Sports/
之前,都能正常工作
我尝试访问这些URL时收到的响应是:
“/”应用程序中出现服务器错误
找不到资源
我已经试过了
在应用程序启动/RouteConfig.cs
:
routes.MapRoute(
name: "CategoriesMapping",
url: "{controller}/{categoryName}",
defaults:
new { controller = "Categoria", action = "Index",
categoryName = URLParameters.Optional
}
);
但是没有成功,问题也是一样的
考虑
其他我已经尝试过的事情:
public ActionResult Index(string? categoryName) { }
及
public ActionResult索引(可为空的categoryName){}
成功?否。当我使用此语法时,Visual Studio返回一个错误
类型“string”必须是不可为null的值类型,才能将其用作泛型类型或方法“System.nullable”中的参数“T”
观察
“正常”是指:如果我访问myapp.com/Category/
,则会为我显示测试
模棱两可的问题?
也许吧。不幸的是,我在这里找到的其他答案——在堆栈上——都不适用于我。我已经试过了,还有其他一些。你应该有这样的路线
routes.MapRoute(
name: "CategoriesMapping",
url: "Category/{categoryName}",
defaults:
new { controller = "Categoria", action = "Index",
categoryName = URLParameters.Optional
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults:
new { controller = "Home", action = "Index",
id = URLParameters.Optional
}
);
请注意,约束要求第一段必须完全是“类别”。这确保默认路由仍然能够处理所有其他请求。您必须保持默认路由,以不打破其他控制器的约定。另外,请确保默认路线是最后映射的。String是引用类型。Nullable仅适用于值类型。
routes.MapRoute(
name: "CategoriesMapping",
url: "Category/{categoryName}",
defaults:
new { controller = "Categoria", action = "Index",
categoryName = URLParameters.Optional
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults:
new { controller = "Home", action = "Index",
id = URLParameters.Optional
}
);