Srinivas Rathikrindi
Srinivas Rathikrindi

Reputation: 576

Is There any way to know that a request is a made using Redirect() method in ASP.NET MVC

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.

Upvotes: 2

Views: 321

Answers (2)

TarasB
TarasB

Reputation: 2428

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"];
    }

Upvotes: 0

haim770
haim770

Reputation: 49105

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

Upvotes: 4

Related Questions