【问题标题】:Is there a way to use identified user 'id' in all views in asp.net MVC?有没有办法在 asp.net MVC 的所有视图中使用已识别的用户“id”?
【发布时间】:2020-04-08 03:24:19
【问题描述】:

我想在所有视图中登录后使用“已识别”用户的“id”,我该怎么做?这是我在控制器中的“登录”:

[AllowAnonymous]
[HttpPost]
public ActionResult Login(string username, string password, bool rememberme)
    {
        UserRepository RepU = new UserRepository();
        if (this.IsCaptchaValid("Captcha is not valid"))
        {
            if (RepU.Exist(username, password))
            {
                string rol = RepU.Where(p => p.Username == username).Single().Roles;
                int ViD = RepU.Where(p => p.Username == username).Single().Id;
                ProductCategoryViewModel vMprocat = new ProductCategoryViewModel();
                RedirectToAction("VisitorAddProduct","AdminPanel",new{id = ViD});
                int timeout = rememberme ? 2880 : 60;
                var ticket = new FormsAuthenticationTicket(username, rememberme, timeout);
                string encrypted = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                FormsAuthentication.SetAuthCookie(username, rememberme);
                cookie.Expires = DateTime.Now.AddMinutes(timeout);
                Response.Cookies.Add(cookie);
                if (rol == "Visitor")
                {
                    return Redirect("/AdminPanel/Dashboard");
                }
                else if (rol == "Customer")
                {
                    return Redirect("/AdminPanel/CustomerHistoryInvoice");
                }
                else if (rol == "GreatAdmin")
                {
                    return Redirect("/AdminPanel/AdminManageStatus");
                }
                else
                {
                    return Redirect("/Home/Index");
                }

            }
         else
            {
                ViewBag.LoginErrorClass = "alert alert-danger";
                ViewBag.LoginErrorStyle = "display:block";
                ViewBag.LoginErrorIcon = "fa fa-frown-o mr-2";
                ViewBag.LoginErrorMessage = "IncorrectUnameorPass";
                return View();
            }
        }
        else
        {
            ViewBag.LoginErrorClass = "alert alert-warning";
            ViewBag.LoginErrorStyle = "display:block";
            ViewBag.LoginErrorIcon = "fa fa-exclamation mr-2";
            ViewBag.LoginErrorMessage = "Incorrectcaptcha!!!";
            return View("Login");
        }
    }

这也是...

    [AllowAnonymous]
    [HttpGet]
    public ActionResult Login()
    {
        if (User.Identity.IsAuthenticated)
        {
            UserRepository repU = new UserRepository();
            string rol = repU.Where(p => p.Username == User.Identity.Name).Single().Roles;

            if (rol == "Visitor")
            {
                return Redirect("/AdminPanel/Dashboard");
            }
            else if (rol == "Customer")
            {
                return Redirect("/AdminPanel/CustomerHistoryInvoice");
            }
            else if (rol == "GreatAdmin")
            {
                return Redirect("/AdminPanel/AdminManageStatus");
            }
            else
            {
                return Redirect("/Home/Index");
            }
        }
        else
        {

            ViewBag.LoginErrorClass = "";
            ViewBag.LoginErrorStyle = "";
            ViewBag.LoginErrorIcon = "";
            ViewBag.LoginErrorMessage = "";
            return View();
        }
    }

现在我想,当登录中的用户身份为“真”时,它的“ID”传递给视图以显示或使用,这是该视图的操作结果.....

[Authorize(Roles = "Visitor")]
    public ActionResult VisitorAddProduct(string CategoryName , string CompanyName, int? page ,int id)
    {
        ProductCategoryViewModel VMprocat = new ProductCategoryViewModel();
        CategoryRepository repCat = new CategoryRepository();
        CompanyRepository repCom = new CompanyRepository();
        ProductRepository repPro = new ProductRepository();
        ScopeRepository repSco = new ScopeRepository();
        ProductStatusRepository repPS = new ProductStatusRepository();
        VMprocat.Category = repCat.Select();
        VMprocat.Company = repCom.Select();
        VMprocat.Scope = repSco.Select();
        VMprocat.ProductStatu = repPS.Select();
        var firstCat = VMprocat.Category.First();

        if (firstCat != null)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            if (String.IsNullOrEmpty(CategoryName))
            {
                CategoryName = firstCat.CategoryName;
            }
            else
            {
                CategoryName = CategoryName.Trim();
            }
            VMprocat.Product = repPro.Where(p => p.Category.CategoryName == CategoryName)
                .ToList().OrderBy(p => p.ProductName).ToPagedList(currentPageIndex, 10);
        }
        else
        {
            VMprocat.Category = null;
        }

        return View("VisitorAddProduct", VMprocat);

    }

这是我的视图模型...

public class ProductCategoryViewModel
{
    public IPagedList<MSCMTestProject3.Models.DomainModels.Product> Product { get; set; }
    public IEnumerable<MSCMTestProject3.Models.DomainModels.Category> Category { get; set; }
    public IEnumerable<MSCMTestProject3.Models.DomainModels.Company> Company { get; set; }
    public IEnumerable<MSCMTestProject3.Models.DomainModels.Scope> Scope { get; set; }
    public IEnumerable<MSCMTestProject3.Models.DomainModels.ProductStatu> ProductStatu { get; set; }
    public int? Id { get; set; }
    public string CategoryName { get; set; }
    public string CompanyName { get; set; }
    public string ScopeName { get; set; }
}

【问题讨论】:

    标签: authentication model-view-controller identity


    【解决方案1】:

    将ID保存为Session变量,每个视图都可以获取;

    示例:

    Session["ID"] = xyz;
    

    xyz = 要传递给另一个视图的变量

    要调用它,只需使用例如:

    @if (Session["ID"] != null)
    {
    your condition
    } 
    

    【讨论】:

    • 谢谢我的朋友,但这样做安全吗?也是另一种方式吗?
    • 我认为这是最安全的方式。即使你被黑了,黑客也只会得到他的 id..
    • 请,如果这回答了你的问题,请投票并检查我的答案:)
    • 我很抱歉,但这对我不起作用...... ;(当我写这个“会话[“UID”] = RepU.Where(p => p.Username == username) .Single().Id;" 我的查看页面失败...
    • 也许可以做 var xyz = RepU.Where(p => p.Username == username).Single().Id;然后 Session["UID"] = xyz;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2018-09-02
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    相关资源
    最近更新 更多