问题
I have a blog post page with comments. Any user (logged in or not) can see a form at the bottom of the page to post a comment. When user enters the comment and she is not authorized - the user is redirected to a login/signup page. After logged in, the user is redirected back to the action, but the POST data, containing the comment body, is lost.
I use the ASP.NET MVC Authorize attribute to require authorization on some actions:
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult Create(int blogPostID, string commentBody) {
var comment = new Comment {
Body = commentBody,
BlogPostID = blogPostID,
UserName = User.Identity.Name
}
// persist the comment and redirect to a blog post page with recently added comment
}
How do you solve this problem?
Making user loggin before displaying the comment form is a bad idea here I think.
Thanks.
回答1:
I would probably just save off the siteId and comment into the Session. Then create another overload for Create that doesn't take any parameters. It checks to see if these variables exist in the session - if so, pass it off to your original Create method.
To do that, you'd have to remove the Authorize attribute and just do the security check yourself. Something like this:
var user = HttpContext.User;
if (!user.Identity.IsAuthenticated)
{
Session["Comment"] = comment;
Session["SiteId"] = siteId;
return RedirectToAction("LogOn", "Account",
new { returnUrl = "/ControllerName/Create"} );
}
Then your overloaded Create:
public ActionResult Create()
{
var comment = (Session["Comment"] ?? "").ToString();
int siteId = 0;
if (Session["siteId"] != null)
siteId = (int)Session["siteId"];
return Create(siteId, comment);
}
Of course, this isn't really all that generic and doesn't handle more complex scenarios, but it's an idea. (hopefully the above code works, I haven't had a chance to test it). It seems like you could maybe do something like this via an action filter but I don't have any sample code for that.
回答2:
You can use hidden field on your authorization form. Put your user's comment to that field (your initial POST data). After that you still can not use the data on your comment form if authorization form simply redirects to your comments form. So make your authorization form post to comments form, data in hidden field will be posted also, so you can use it.
来源:https://stackoverflow.com/questions/10096700/asp-net-mvc-preserve-post-data-after-authorize-attribute-login-redirect