【问题标题】:Redirect to Action not working using MVC asp.net使用 MVC asp.net 重定向到操作不起作用
【发布时间】:2019-03-11 09:12:31
【问题描述】:

我有一个要求,我使用 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 }               
        );

    }

Ajax 调用

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 () {
            
        }
    });
}

【问题讨论】:

  • 您确定App 是您的控制器名称吗? RedirectToAction参数的顺序是先传递动作名,后传控制器名。
  • @TetsuyaYamamoto:我也尝试了相反的方法,但仍然没有任何反应
  • 在你的ActionResult 末尾我发现了return Json(strReturn),这个动作是从AJAX 调用的吗?如果使用AJAX调用,当然不能使用RedirectToAction重定向,需要在客户端脚本中使用location.href@Url.Action()
  • @TetsuyaYamamoto:是的,我添加了一个 ajax 调用。另请参阅我更新的问题以获取更多信息
  • @TetsuyaYamamoto:你能告诉我如何使用 mvc 和 ajax。

标签: c# asp.net-mvc model-view-controller windows-authentication


【解决方案1】:

您的路线配置无法区分您提供的两条路线,因为它们没有区别。此外,您的默认路线应始终位于最后。请将路由配置更改为:

注意,我更改了您的“分配”路由的 url,并在末尾移动了“默认”路由。

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 }

    );

}

【讨论】:

  • 您的 RedirectToAction 看起来如何?使用RedirectToAction("Assign", "App");return RedirectToAction("Certify", "App");return RedirectToAction("Approver", "App"); 尝试上述答案中的路由配置
  • App 控制器中的“Assign”、“Certify”和“Approver”操作方法是什么样的?他们接受任何参数吗?
【解决方案2】:

由于您使用 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 }
    );

}

【讨论】:

【解决方案3】:

所以你有一个像这样的当前 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 语句的偏好完全取决于你

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多