Antoine Pelletier
Antoine Pelletier

Reputation: 3316

Why does Redirect() function tries to redirect me inside the same controller

I'm building a return URL by concatenating many string variables, but for the sake of testing, I used a test string.

It works perfectly in the login function of the account controller :

[HttpPost]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    /* irrelevant code lines */

    return Redirect( "SuiviFinancier/Niveau2?unitAdm=012"    /*returnUrl*/);
}

this redirect to the right route : /SuiviFinancier/Niveau2?unitAdm=012

But that redirect function used in another controller, makes it automatically add the controller name before the string, exemple :

public class paramsVisuelController : Controller
{
    
    [HttpPost]
    public ActionResult Options(ParamsVisuel model)
    {
        return Redirect( "SuiviFinancier/Niveau2?unitAdm=012" );

    }
}

The output route here is : /paramsVisuel/SuiviFinancier/Niveau2?unitAdm=012

Why is that ? MVC is adding the controller name before my string ? But I don't want that. It is a complete route including the controller so why would I want the current controller name to be added before it ? It's non-sens.

Description : HTTP 404.

URL demandée: /paramsVisuel/SuiviFinancier/Niveau2

Upvotes: 0

Views: 80

Answers (1)

Antoine Pelletier
Antoine Pelletier

Reputation: 3316

Usually, one should use this function for redirection :

RedirectToAction("Niveau2", "SuiviFinancier", new { unitAdm = 012 });

Which is the classic MVC way to redirect to an action in a controller.

But if, for some reason, you need the redirect() function to work properly, don't forget to begin your string whit a slash if it's a complete path :

return Redirect( "/SuiviFinancier/Niveau2?unitAdm=012");

or a tilt and a slash :

return Redirect( "~/SuiviFinancier/Niveau2?unitAdm=012");

Upvotes: 1

Related Questions