Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Checking for ReturnUrl in Razor View

0.00/5 (No votes)
18 Jun 2012 1  
Quick way to modify the logon view depending on if the user has been redirected.

Introduction

I was looking for a quick way to modify the logon view depending on if the user was doing a standard login or was being redirected to login as a result of not having the suitable roles.

The Controller

In the controller, the Action might have the following;

[Authorize(Roles = "Admin-Can-Create")]
public ActionResult Create()
{
  //Do whatever
  return View();
}

If the current user is not authenticated or does not have the "Admin-Can-Create" role, then the page will be directed to the login view. Now, the user might wonder why they have been redirected to the login view if for example they are already logged in.

Not looking for anything fancy or complicated, just plain old keep it simple, just want to modify the text displayed.

The obvious thing that occurred to me was that when the user was redirected to the logon page due to a lack of suitable Role, the query string contains the ReturnUrl parameter, with the path to return to on completion of the authentication.

Excellent, I will just check for the appearance of this parameter and that will do.

The View

Adding a simple check in the Razor view and what I now have is:

@if (Url.RequestContext.HttpContext.Request.QueryString.AllKeys.Contains("ReturnUrl"))
{
    //ReturnUrl Present
    <h2>Insufficient Permissions</h2>
    <p style="color: Red">You may have arrived at this page 
    if you have tried to perform an action for which you do not have the 
    necessary permissions and require a higher level of access.</p>
}
else
{
    //Standard Display
    <h2>Log On</h2>
    <p>
       Please enter your user name and password to logon. 
    </p> 
}      

What the code is doing is getting a string array of all the keys present in the query string and then checking for the existence of one named ReturnUrl.

This approach means the user does not get a warning if they have elected to select the Logon button and go to the logon page deliberately and will only see the modified view if they are being taken there due to for example lack of permissions.

This is simple and serves my needs for the quick check I needed.

History

  • V1.0 - 18th June 2012

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here