2

Here i want to check the request type, If request is coming from Redirect() method in my applicaton Add some message to ViewBag to show on Login page Else don't add message (where user opens login page directly)

 public ActionResult Login()
    {           
    //if(RequestIsARedirect)
        //ViewBag.LoginMessage = "Please login to Continue";
        return View();
    }

Thanks in advance.

2 Answers2

4

Wouldn't it be easier if you'll redirect with a parameter?

return RedirectToAction("Login", "Account", new { returnUrl = this.Request.Url });

Or

return Redirect("/Account/Login?returnUrl=' + this.Request.Url });

Then check that returnUrl parameter:

public ActionResult Login(string returnUrl)
{           
     if (!String.IsNullOrEmpty(returnUrl))
        ViewBag.Message = "Please login to continue";
}

Also, if you'll use the built-it [Authorize] action-filter, it will automatically add the returnUrl as parameter to the login Url when redirecting.

See MSDN

haim770
  • 48,394
  • 7
  • 105
  • 133
0

The way to do it without adding extra url params is using TempData, which is The data stored ... for only one request.. http://msdn.microsoft.com/en-us/library/system.web.mvc.viewpage.tempdata(v=vs.118).aspx

The code would be like this then:

    public ActionResult EntryPoint()
    {
        TempData["CameFromEntryPoint"] = true;
        return Redirect("Login");
    }

    public ActionResult Login()
    {
        if(RequestIsARedirect())
            ViewBag.LoginMessage = "Please login to Continue";
        return View();
    }

    private bool RequestIsARedirect()
    {
        return TempData["CameFromEntryPoint"] != null && (bool) TempData["CameFromEntryPoint"];
    }
TarasB
  • 2,407
  • 1
  • 24
  • 32
  • 1
    Actually, TempData stores data only for one read from TempData. It has nothing to do with the request. You can put something in TempData, and go to 5 other pages, then read it out of TempData and it will still be there if it hasn't already been read. Unfortunately, the documentation doesn't seem to have been updated when this behavior changed back in.. I think MVC2 or MVC3. – Erik Funkenbusch Oct 30 '14 at 08:33
  • That is a good addition, thanks @Erik Funkenbusch. Having that behavior in mind it is important to do a `TempData` assignement right before `Redirect`, and in the redirected action read it as a first thing. Here is a debate about the topic to find more of pros/cons and decide use it or not - http://stackoverflow.com/questions/386681/asp-net-mvc-tempdata-good-or-bad-practice. – TarasB Oct 30 '14 at 08:52
  • `TempData` relies on Session. Personally I don't like to store a new session object for someone who didn't authenticate yet. – haim770 Oct 30 '14 at 22:36