ASP.NET MVC-授权属性登录重定向后保留POST数据 [英] ASP.NET MVC - Preserve POST data after Authorize attribute login redirect

查看:72
本文介绍了ASP.NET MVC-授权属性登录重定向后保留POST数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个博客评论页面.任何用户(无论是否登录)都可以在页面底部看到一个表单以发表评论.当用户输入评论但未获得授权时-用户将被重定向到登录/注册页面.登录后,用户将被重定向回到操作,但是包含注释正文的POST数据将丢失.

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.

我使用ASP.NET MVC Authorize属性要求对某些操作进行授权:

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
}

您如何解决此问题?

在我看来,在显示评论表单之前进行用户登录是一个坏主意.

Making user loggin before displaying the comment form is a bad idea here I think.

谢谢.

推荐答案

我可能只是保存siteId并在Session中添加注释.然后为Create创建另一个不带任何参数的重载.它会检查会话中是否存在这些变量-如果存在,请将其传递给原始的Create方法.

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.

为此,您必须删除Authorize属性,然后自己进行安全检查.像这样:

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

然后重载创建:

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.

这篇关于ASP.NET MVC-授权属性登录重定向后保留POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆