C# MVC路由仅适用于某些操作结果
我是否必须为控制器中的每个操作结果发送一条特殊的路径,或者您是否只发送一条路径,并且必须按照控制器认为的标准生活?我想您可以创建一个默认路由,然后为您想要的任何实例创建一个特殊路由。我一直遇到这样一个问题:我的一条路线将正确地命中我的操作结果,但其他路线不再有效。此代码可能是错误的方式,但因此我将其发布在这里。如果可以的话,请尝试为我澄清这一点。例如,我理解我应该能够执行{controller}/{action}/{id}。因此,对于以下内容,应该点击Settings/GetSite/{siteid}C# MVC路由仅适用于某些操作结果,c#,asp.net-mvc,asp.net-mvc-routing,C#,Asp.net Mvc,Asp.net Mvc Routing,我是否必须为控制器中的每个操作结果发送一条特殊的路径,或者您是否只发送一条路径,并且必须按照控制器认为的标准生活?我想您可以创建一个默认路由,然后为您想要的任何实例创建一个特殊路由。我一直遇到这样一个问题:我的一条路线将正确地命中我的操作结果,但其他路线不再有效。此代码可能是错误的方式,但因此我将其发布在这里。如果可以的话,请尝试为我澄清这一点。例如,我理解我应该能够执行{controller}/{action}/{id}。因此,对于以下内容,应该点击Settings/GetSite/{site
public ActionResult GetSite(int id);
路由配置:
routes.MapRoute(
"SettingsUpdateEnviorment",
"{controller}/{action}",
new { controller = "Settings", action = "UpdateProperties" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
name: "ProfileRoute",
url: "Profiles/{userId}",
defaults: new
{
controller = "Profile",
action = "Index",
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Settings", // Route name
"Settings/{id}", // URL with parameters
new { controller = "Settings", action = "Index" } // Parameter defaults
);
控制器代码:
public ActionResult Index(int id)
{
return View(model);
}
public ActionResult GetSite(int enviornmentID, string name)
{
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddSite(int id)
{
return RedirectToAction("Index", new { id = id });
}
因此,URL的工作方式与Settings/1所预期的一样,以命中索引actionresult Index(intID)。然后,当我尝试使用以下actionLink为GetSite(int EnvironmentId,string name)执行ActionResult时:
@Html.ActionLink(site.Name, "GetSite", "Settings", new { enviornmentID = Model.Enviorment.EnvironmentID, name = site.Name }, null)
它按如下方式正确创建URL:Settings/GetSite?environmentid=1&name=CaseyTesting2,但给出一个错误,指出我正在尝试向索引(int-id)actionResult发送空值。我想,既然我使用的是动作名称和相同的参数,MVC会找出路线吗?为什么这对我不起作用,或者我做错了什么?谢谢 多亏了这篇文章,我才意识到自己在做什么。我把订单弄乱了,其他的都搞定了。然后,当其他一切都是正确的时候,我错过了相同的参数名称。所以我在试图找出问题的时候总是遇到一些小问题。我还切换到MVC5的属性路由,并且更喜欢它 这是我现在正在使用的代码: 路由配置
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "ProfileRoute",
url: "Profiles/{userId}",
defaults: new
{
controller = "Profile",
action = "Index",
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
控制器代码
[Authorize]
[RoutePrefix("settings")]
[Route("{action=index}")]
public class SettingsController : ZenController
{
[Route("{id:int}")]
public ActionResult Index(int id)
{
return View(model);
}
[Route("GetSite/{sitename:alpha}")]
public ActionResult GetSite(string sitename)
{
return RedirectToAction("Index");
}
再次感谢大家!快乐编码 我提前向您道歉,因为这是我关于路线的第四个问题(通常我会立即理解),我的想法是一样的。无论出于什么原因,我都会对这条路线产生真正的问题。我知道默认设置是如何工作的,但当我尝试定制时,我会把一切搞砸(