Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 控制器过载指标法 目标_C#_Asp.net Mvc 4 - Fatal编程技术网

C# 控制器过载指标法 目标

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 {

重载“Index”方法,使其类似于
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 
             }
 );