0

Is it possible to check in an action, which action it was called by?

Sounds a little bit confusing but i try to explain in a short example

public IActionResult CallerAction1(){
    return Redirect("CalledAction")
}

public IActionResult CallerAction2(){
    return Redirect("CalledAction")
}

public IActionResult CalledAction(){
    // Who called me? Who redirected to me? 1 or 2?
    return View();
}
tereško
  • 58,060
  • 25
  • 98
  • 150
flexwend
  • 47
  • 7
  • Possible duplicate of [Getting the HTTP Referrer in ASP.NET](https://stackoverflow.com/questions/4258217/getting-the-http-referrer-in-asp-net) – mai Sep 25 '19 at 14:13

3 Answers3

1

No, not really. A redirect is a response in itself. It has a 301, 302 or 307 status code and a Location response header which contains the URL you are "redirecting" to. At that point it's done.

The client then may opt to send a new request for the URL that was in the Location header, and web browsers do by default. However, that's a brand new request, totally unrelated to the first that resulted in the redirect. HTTP is a stateless protocol, so each request is just as if it's the first the client has ever made with the server.

That said, there may be a Referer (sic) header attached to the request, and if so, this may contain the URL that was previously requested, but that's a client implementation detail, and not guaranteed or reliable (it can be spoofed).

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

Just as in code, where you shouldn't care which method called the current method, you shouldn't care which action redirected to the current action.

If you take a step back and realise why you want to know this, you probably want to do something different based on the circumstances. In that case, you use parameters. And each caller passes a different parameter.

How to name this parameter, depends on what you want it to do. So, for example:

public IActionResult CalledAction(bool withFullDetails){
}

public IActionResult CallerAction1(){
    return RedirectToAction("CalledAction", new { withFullDetails = false });
}

public IActionResult CallerAction2(){
    return RedirectToAction("CalledAction", new { withFullDetails = true });
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

You could pass the action name or request path as query string and get it in CalledAction,for example

public IActionResult CallerAction1()
    {
        string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
        string requestPath = Request.Path.ToString();
        return RedirectToAction("CalledAction",new { path = requestPath, name = actionName });

    }

    public IActionResult CalledAction()
    {
        var fromPath = HttpContext.Request.Query["path"].ToString();
        var fromActionName= HttpContext.Request.Query["name"].ToString();

        // Who called me? Who redirected to me? 1 or 2?
        return View();
    }
Ryan
  • 19,118
  • 10
  • 37
  • 53