[英]Redirect to Action not working using MVC asp.net
我有一個要求,在此我可以使用Windows身份驗證來驗證用戶。 到那里為止,它工作得很好。 但是,當我嘗試重定向到各自的controllers
它什么也沒做。
下面是我的代碼。
public ActionResult ValidateUser(string strUsername, string strPassword)
{
string strReturn = "";
string strDbError = string.Empty;
strUsername = strUsername.Trim();
strPassword = strPassword.Trim();
UserProviderClient ObjUMS = new UserProviderClient();
bool result = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);
Session["isUserAuthenticated"] = result;
if (result == true)
{
Session["isUserOutsideINDomain"] = true;
Session["OutsideINDomainUsername"] = strUsername;
//redirect to respective controller
UMS ObjUMSDATA = new UMS();
string strUserName = "";
string strCurrentGroupName = "";
int intCurrentGroupID = 0;
strUserName = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
_UMSUserName = strUserName;
if (!string.IsNullOrEmpty(strUserName))
{
List<UMSGroupDetails> lstUMSGroupDetails = null;
List<UMSLocationDetails> lstUMSLocationDetails = null;
ObjUMSDATA.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
if (strCurrentGroupName != "" && intCurrentGroupID != 0)
{
ViewBag.LoginUserName = strUserName.ToUpper();
ViewBag.CurrentGroupName = strCurrentGroupName;
ViewBag.CurrentGroupID = intCurrentGroupID;
ViewBag.GroupDetails = lstUMSGroupDetails;
ViewBag.LocationDetails = lstUMSLocationDetails;
TempData["Location"] = lstUMSLocationDetails;
TempData["strCurrentGroupName"] = strCurrentGroupName;
TempData.Keep();
if (strCurrentGroupName == "NEIQC_SAP_ENGINEER")
{
return RedirectToAction("Assign","App"); // here its not redirecting properly.
}
else if (strCurrentGroupName == "NEIQC_FIBER_ENGINEER")
{
return RedirectToAction("App", "Certify");
}
else if (strCurrentGroupName == "NEIQC_CMM")
{
return RedirectToAction("App", "Approver");
}
}
else
{
return RedirectToAction("ErrorPage", "UnAuthorize");
}
}
}
else
{
strReturn = "Login UnSuccessful";
}
return Json(strReturn);
}
請幫助為什么它不起作用
更新
我的路線配置詳細信息。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Assign",
url: "{controller}/{action}/{id}",
defaults: new { controller = "App", action = "Assign", id = UrlParameter.Optional }
);
}
阿賈克斯電話
function validateUser() { var getUserName = $('#txtUsername').val(); var getPassword = $('#txtPassword').val(); // console.log(getUserName); //console.log(getPassword); var Values = { "strUsername": getUserName, "strPassword": getPassword }; $.ajax({ url: AppConfig.PrefixURL + "Home/ValidateUser", dataType: 'json', type: 'post', contentType: 'application/json', data: JSON.stringify(Values), processData: false, success: function () { }, error: function () { } }); }
您的路由配置無法區分您給定的兩條路由,因為它們沒有區別。 另外,您的默認路由應始終位於末尾。 請更改路由配置為:
注意,我更改了“分配”路由的網址,並在最后移動了“默認”路由。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Assign",
url: "App/{action}/{id}",
defaults: new { controller = "App", action = "Assign", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
);
}
由於您是使用AJAX調用控制器操作的,因此RedirectToAction
顯然無法在其中運行,因為AJAX調用旨在保留在同一頁面中。 您應該為所有響應返回JSON字符串,並在客戶端腳本上使用switch...case
塊或if-condition重定向到相應的動作,並使用location.href
和@Url.Action()
幫助程序生成URL字符串:
[HttpPost]
public ActionResult ValidateUser(string strUsername, string strPassword)
{
string strReturn = "";
string strDbError = string.Empty;
strUsername = strUsername.Trim();
strPassword = strPassword.Trim();
UserProviderClient ObjUMS = new UserProviderClient();
bool result = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);
Session["isUserAuthenticated"] = result;
if (result == true)
{
Session["isUserOutsideINDomain"] = true;
Session["OutsideINDomainUsername"] = strUsername;
//redirect to respective controller
UMS ObjUMSDATA = new UMS();
string strUserName = "";
string strCurrentGroupName = "";
int intCurrentGroupID = 0;
strUserName = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
_UMSUserName = strUserName;
if (!string.IsNullOrEmpty(strUserName))
{
List<UMSGroupDetails> lstUMSGroupDetails = null;
List<UMSLocationDetails> lstUMSLocationDetails = null;
ObjUMSDATA.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
if (strCurrentGroupName != "" && intCurrentGroupID != 0)
{
ViewBag.LoginUserName = strUserName.ToUpper();
ViewBag.CurrentGroupName = strCurrentGroupName;
ViewBag.CurrentGroupID = intCurrentGroupID;
ViewBag.GroupDetails = lstUMSGroupDetails;
ViewBag.LocationDetails = lstUMSLocationDetails;
TempData["Location"] = lstUMSLocationDetails;
TempData["strCurrentGroupName"] = strCurrentGroupName;
TempData.Keep();
// here you need to return string for success result
return Json(strCurrentGroupName);
}
else
{
return Json("Error");
}
}
}
else
{
strReturn = "Login UnSuccessful";
}
return Json(strReturn);
}
AJAX電話
$.ajax({
url: AppConfig.PrefixURL + "Home/ValidateUser",
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify(Values),
processData: false,
success: function (result) {
switch (result) {
case 'NEIQC_SAP_ENGINEER':
location.href = '@Url.Action("Assign", "App")';
break;
case 'NEIQC_FIBER_ENGINEER':
location.href = '@Url.Action("Certify", "App")';
break;
case 'NEIQC_CMM':
location.href = '@Url.Action("Approver", "App")';
break;
case 'Error':
location.href = '@Url.Action("ErrorPage", "UnAuthorize")';
break;
case 'Login UnSuccessful':
// do something
break;
// other case options here
}
},
error: function (xhr, status, err) {
// error handling
}
});
附加說明:
RouteConfig
將從最特定的路由路由到更通用的路由,因此Default
路由必須在最后聲明,自定義路由定義必須與默認路由不同。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Assign",
url: "App/{action}/{id}",
defaults: new { controller = "App", action = "Assign", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
);
}
因此,您當前有一個這樣的ajax調用:
$.ajax({
url: AppConfig.PrefixURL + "Home/ValidateUser",
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify(Values),
processData: false,
success: function () {
},
error: function () {
}
});
很好,但是目前成功不起作用。 您有一個返回字符串的控制器方法
return Json(strReturn);
現在,我希望您不要返回該值,而是將角色作為字符串返回。
我希望您的ajax類似於此:
$.ajax({
url: AppConfig.PrefixURL + "Home/ValidateUser",
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify(Values),
processData: false,
success: function (result) {
//Here we will be returning the role as a string from the first ajax call and using it to check against in here
//I just want you to essentiatly do the if statements in the controller here such as this
if(result == "NEIQC_SAP_ENGINEER")
{
window.location.href = '@url.Action("Assign", "App")'
}
},
error: function () {
}
});
編輯:此答案似乎與@TetsuyaYamamoto的非常相似。 兩者都應該起作用,但是是否使用switch語句的偏好完全取決於您
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.