[英]ASP.net mvc ActionResult parameter
My controller looks like this: 我的控制器看起来像这样:
public ActionResult Index(string username)
{
if (string.IsNullOrEmpty(username))
{
_userId = User.Identity.GetUserId();
}
else
{
var user = UserService.GetUserByUserName(username);
if (user != null)
{
_userId = user.Id;
}
else
{
return RedirectToAction("Index", "Routines");
}
}
return View();
}
[HttpGet]
public JsonResult GetUserHomeData()
{
return Json(CreateHomeViewModel(), JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetUserStatisticsOverview()
{
return Json(CreateUserStatisticsOverviewViewModel(), JsonRequestBehavior.AllowGet);
}
And I have problem with parameter username of ActionResult Index. 而且我对ActionResult Index的参数用户名有疑问。 I've monitored username variable and if I type url like this: www.test.com/profile/someUserName
我监视了用户名变量,如果我输入这样的url:www.test.com/profile/someUserName
Variable username is assigned these values: 为变量用户名分配以下值:
1. someUserName 1. someUserName
2. GetUserHomeData 2. GetUserHomeData
3. GetUserStatisticsOverview 3. GetUserStatisticsOverview
I call these Get methods from my javaScript file, why is this happening and how can I prevent this, ie catch only "someUsername" 我从我的javaScript文件中调用这些Get方法,为什么会发生这种情况,如何防止这种情况,即只捕获“someUsername”
Here is my route config: 这是我的路线配置:
routes.MapRoute("Profile", "profile/{userName}",
new { controller = "Profile", action = "Index", userName = UrlParameter.Optional }
);
routes.MapRoute("Default", "{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Here is how I access Get methods (I'm using Angular's $http) 以下是我访问Get方法的方法(我使用的是Angular的$ http)
getResult: function() {
var input = $http.get("/Profile/GetUserHomeData");
var deferred = $q.defer();
deferred.resolve(input);
return deferred.promise;
}
Problem is you are probably calling something like: @Url.Action("GetUserHomeData", "Profile")
inside your JS, but this will be catched by the first route and the action there is Index
and nothing else. 问题是你可能在你的JS里面调用类似:
@Url.Action("GetUserHomeData", "Profile")
,但是这将被第一条路线@Url.Action("GetUserHomeData", "Profile")
并且其中的操作是Index
而不是其他任何东西。 You can eliminate the problem by just removing the route 您可以通过删除路线来消除此问题
routes.MapRoute("Profile", "profile/{userName}",
new { controller = "Profile", action = "Index", userName = UrlParameter.Optional }
);
alternatively you can rewrite the rule (that it does not match the controller-name): 或者你可以重写规则(它与控制器名称不匹配):
routes.MapRoute("ProfileShortRoute", "p/{userName}",
new { controller = "Profile", action = "Index", userName = UrlParameter.Optional }
);
This will lead to Urls like this: http://domain/Profile/?userName=someUser
or http://domain/p/someUser
这会导致Urls像这样:
http://domain/Profile/?userName=someUser
或http://domain/p/someUser
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.