views:

131

answers:

1

In order to preserve post data after utilizing the [Authorize] attribute on a controller method, which then redirects the user to a login page, which then upon successful authentication redirects the user to where they were intending to go -- how would this be done? The original form submission is not relayed by default. A response to a previous posting said to:

You need to serialize your form values and a RedirectUrl to a hidden field. After authentication deserialize the data in your hidden field and redirect based on the value of the RedirectUrl. You will need a custom Authorize class to handle this.

My question is -- any examples to further point me in the right direction? Yes, I can add a [Serialize] tag to the controller class but I can't figure out how creating a custom Authorize class would help? I see plenty of material online on creating a custom Authorize class but where would the de-serialization be done? It would help greatly if you could go one or two levels deeper. I'm a newbie.

(I would comment on the previous posting but I'm new to the site and have not amassed enough points. I would also put a link to the other posting but it says new users can't show links either!)

A: 

You can create a custom authorization attribue that store the form posted values in the Session dictionary, and then after the authorization has completed you can resotre the values from the Session dictionary.
Here is an example:

public class CustomAuth:AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      var form = filterContext.HttpContext.Request.Form;
      if (form.HasKeys()) {
       foreach(var key in form.AllKeys)
       {
         filterContext.HttpContext.Session[key]= form[key];
       }
      }
      base.OnAuthorization(filterContext);
    }
}

As you see, before the authorization all the form values are stored in the session.
Now after the authorization has completed you can restore all the values.

[CustomAuth()]
public ActionResult Admin()
{
   // supposing you had a from input with the name "Name"
   string Name = Session["Name"] ?? string.Empty;

   return View();
}
Marwan Aouida