1

I have a requirement, where I validate user using Windows Authentication. Till there it works perfectly fine. But when I try to redirect to respective controllers it does nothing.

Below is my code:

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

Why is it not working?

Update

My route config details.

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 call

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 () {
            
        }
    });
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Nad
  • 4,605
  • 11
  • 71
  • 160
  • Are you sure that `App` is your controller name? The order of [`RedirectToAction`](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.redirecttoaction?view=aspnet-mvc-5.2) parameters is action name passed first, followed by controller name. – Tetsuya Yamamoto Mar 11 '19 at 09:15
  • @TetsuyaYamamoto: I tried the other way round too, but still nothing happens – Nad Mar 11 '19 at 09:16
  • On the end of your `ActionResult` I spotted `return Json(strReturn)`, is this action called from AJAX? If it uses AJAX call, of course you cannot use `RedirectToAction` to redirect, you need to use `location.href` with `@Url.Action()` in client-side script instead. – Tetsuya Yamamoto Mar 11 '19 at 09:18
  • @TetsuyaYamamoto: Yes, I have added an ajax call. Also see my updated question for more info – Nad Mar 11 '19 at 09:20
  • @TetsuyaYamamoto: can u tell me how to do it using mvc and ajax. – Nad Mar 11 '19 at 09:22
  • Can you not just add another ajax in the success? – JamesS Mar 11 '19 at 09:26
  • @JamesS: sure, but what to add. let me know – Nad Mar 11 '19 at 09:26
  • Just to the exact same as you have above but in the ajax return append the result from the controller to in the `url` section of the new ajax call and call that controller – JamesS Mar 11 '19 at 09:34
  • @JamesS: it would be great if u write it in an answer section and let me know – Nad Mar 11 '19 at 09:35
  • I've added my answer below – JamesS Mar 11 '19 at 09:56

3 Answers3

0

Your route config cannot differentiate between two routes that you have given because they are not different. Also, your default route should always be at the end. Kindly change route config to this:

Notice, I changed the url for your "Assign" route and moved "Default" route at the end.

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 }

    );

}
prinkpan
  • 2,117
  • 1
  • 19
  • 32
  • How does your RedirectToAction look like? Try the route config in the answer above with `RedirectToAction("Assign", "App");` or `return RedirectToAction("Certify", "App");` or `return RedirectToAction("Approver", "App");` – prinkpan Mar 11 '19 at 09:33
  • What does your "Assign", "Certify" and "Approver" actionmethod in App controller look like? Do they accept any parameters? – prinkpan Mar 11 '19 at 09:36
0

Since you're calling the controller action using AJAX, obviously RedirectToAction won't work there because AJAX call intended to stay in the same page. You should return JSON string for all responses and use switch...case block or if-condition on client-side script to redirect into corresponding actions, with location.href and @Url.Action() helper to generate URL string:

[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 call

$.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
    }
});

Additional note:

The RouteConfig process routes from most-specific to more-general routes, hence Default route must be declared in last place, and custom route definition must be different from default one.

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

}
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
0

So you have a current ajax call such as this:

$.ajax({
    url: AppConfig.PrefixURL + "Home/ValidateUser",
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify(Values),
    processData: false,
    success: function () {
    },
    error: function () {

    }
});

This is fine however the success does nothing at the moment. You have a controller method that returns the string

return Json(strReturn);

Now I want you to instead of returning that, return the role instead as a string.

I want your ajax to resemble this:

$.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 () {

    }
});

EDIT: This answer seems to be very similar to @TetsuyaYamamoto 's. Both should work however the preference of whether or not to use a switch statement is completely up to you

JamesS
  • 2,167
  • 1
  • 11
  • 29