【问题标题】:ASP NET Is there another way to copy value from current function in controller to another controller without using RedirectToAction?ASP NET 是否有另一种方法可以在不使用 RedirectToAction 的情况下将值从控制器中的当前函数复制到另一个控制器?
【发布时间】:2020-12-14 01:52:19
【问题描述】:

对不起,如果我没有正确写出我的问题,但我会尝试更详细地描述我的情况。 我正在开发用于存储文本文件的应用程序。这个应用程序的想法是:用户创建帐户(注册视图),登录(登录视图),之后这个用户可以查看我的本地数据库(在 sql server 中管理)在 WebGrid 视图中的所有文本文件。 问题是将 UserID 值从登录视图传输到 WorkSpaceController 中的 UploadFile 函数。我使用“public ActionResult Login(UserDataClass log)”中的 RedirectToAction 在 FileManager 函数(显示 WebGridView)中传输记录的用户电子邮件。函数获取此 useremail 值并使用它通过 SqlConnection 获取 UserID,最终通过完成查询“从 UserData 内部连接 ​​FileData 中选择”来获取用户拥有的所有文件。 FileData 的外键是“UserID”,所以我用它来将文件上传到当前登录的用户到我的数据库。 最后的问题是将“useremail”值从“Login func”或“FileManager”传输到 UploadFile 以再次获取 id 并有机会将文件上传到当前用户的 dbo.FileData。

希望您能帮我解决这个问题吗?由于情况,我不使用实体框架进行此操作。

如果我描述的细节不正确,如果需要,我会写更多的细节。

用户数据控制器

public class UserDataController : Controller
{
    string constr = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
    // GET: UserData
    [HttpGet]
    public ActionResult Login()
    {
        return View();
    }
    public ActionResult Registration()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Registration(UserDataClass reg) //Создание аккаунта
    {
        string connection = "Data Source=DESKTOP-LRLFA5K\\SQLEXPRESS;Initial Catalog=FileCloud;Integrated Security=True";
        using (SqlConnection sqlcon = new SqlConnection(connection))
        {
            string sqlquery = "insert into UserData(UserName, UserEmail, UserPassword) values('" + reg.UserName + "','" + reg.UserEmail + "','" + reg.UserPassword + "')";
            using (SqlCommand sqlcom = new SqlCommand(sqlquery, sqlcon))
            {
                sqlcon.Open();
                sqlcom.ExecuteNonQuery();
                sqlcon.Close();
            }
        }
        return View(reg);
    }
    [HttpPost]
    public ActionResult Login(UserDataClass log) //Авторизация
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=DESKTOP-LRLFA5K\\SQLEXPRESS;Initial Catalog=FileCloud;Integrated Security=True;MultipleActiveResultSets=True";
        SqlDataReader dr;
        con.Open();
        SqlCommand com = new SqlCommand("select * from UserData where UserEmail ='" + log.UserEmail + "' and UserPassword ='" + log.UserPassword + "'", con);
        dr = com.ExecuteReader();
        if (dr.Read())
        {
            Session["useremail"] = log.UserEmail.ToString();
            return RedirectToAction("FileManager", "WorkSpace", new { useremail = log.UserEmail.ToString()});
        }
        else
        {
            ViewData["Message"] = "Неправильное имя пользователя или пароль";
        }
        con.Close();
        return View();
    }

工作空间控制器

public class WorkSpaceController : Controller
{
    string constr = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
    WorkSpaceClass ws = new WorkSpaceClass();
    List<WorkSpaceClass> _ws = new List<WorkSpaceClass>();
    // GET: WorkSpace
    public ActionResult Add()
    {
        return View();
    }
    public ActionResult UploadFile(string useremail)
    {
        UserDataClass info = new UserDataClass();
        info.UserEmail = Session["username"].ToString();
        SqlConnection sqlcon = new SqlConnection(constr);
        string comman = "select UserID from UserData where UserEmail = '" + info.UserEmail + "'"; //??? Вероятно, Email пуст...
        using (SqlCommand sqlcom = new SqlCommand(comman, sqlcon))
        {
            sqlcon.Open();
            TempData["UserID"] = sqlcom.ExecuteScalar();
        }
        //ws.UserID = id; //UserID не читается
        sqlcon.Close();
        return View();
    }
    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase doc, string useremail) //Загружаем текстовый файл в БД
    {
        ViewBag.UserEmail = useremail;
        if (doc != null)
        {
            ws.FileName = Path.GetFileName(doc.FileName);
            ws.FileData = new byte[doc.ContentLength];
            doc.InputStream.Read(ws.FileData, 0, doc.ContentLength);
            ws.FileExtension = Path.GetExtension(ws.FileName);
            DateTime FileDate = DateTime.Now;

            SqlConnection sqlcon = new SqlConnection(constr);

            ws.FileDate = FileDate.ToString("dd/MM/yyyy");
            if (ws.FileExtension == ".doc" || ws.FileExtension == ".docx" || ws.FileExtension == ".txt" || ws.FileExtension == ".pdf")
            {
                string FilePath = Path.Combine(Server.MapPath("~/FileData"), ws.FileName); //Указываем дирректорию хранения файла
                doc.SaveAs(FilePath); 
                string command = "insert into FileData(FileName, FileData, FileExtension, FileDate, UserID) values(@FileName, @FileData, @FileExtension, @FileDate, @UserID)";
                sqlcon.Open();
                SqlCommand sqlcom = new SqlCommand(command, sqlcon);
                sqlcom.Parameters.Add("@FileName", SqlDbType.VarChar).Value = ws.FileName;
                sqlcom.Parameters.Add("@FileData", SqlDbType.VarBinary).Value = ws.FileData;
                sqlcom.Parameters.Add("@FileExtension", SqlDbType.VarChar).Value = ws.FileExtension;
                sqlcom.Parameters.Add("@FileDate", SqlDbType.VarChar).Value = ws.FileDate;
                sqlcom.Parameters.Add("@UserID", SqlDbType.Int).Value = (int)TempData["UserID"];
                sqlcom.ExecuteNonQuery();
                sqlcon.Close();
            }
        }
        return View(ws);
    }

    public ActionResult FileManager(WorkSpaceClass wsc, string useremail)
    {
        UserDataClass info = new UserDataClass();
        info.UserEmail = useremail;
        SqlConnection sqlcon = new SqlConnection(constr);
        string comman = "select UserID from UserData where UserEmail = '" + info.UserEmail + "'"; //??? Вероятно, Email пуст...
        using (SqlCommand sqlcom = new SqlCommand(comman, sqlcon))
        {
            sqlcon.Open();
            TempData["UserID"] = sqlcom.ExecuteScalar();
        }
        sqlcon.Close();
        List<WorkSpaceClass> list = new List<WorkSpaceClass>();
        DataTable dtFiles = GetFileDetails();
        foreach (DataRow dr in dtFiles.Rows)
        {
            list.Add(new WorkSpaceClass
            {
                FileName = @dr["filename"].ToString(),
                FileExtension = @dr["fileextension"].ToString(),
                FileDate = @dr["filedate"].ToString(),
                FileURL = dr["fileurl"].ToString()
            }); ;
        }
        wsc.FileList = list;
        return View(wsc);
    }

    private DataTable GetFileDetails()
    {
        DataTable dtData = new DataTable();
        SqlConnection con = new SqlConnection(constr);
        con.Open();
        SqlCommand command = new SqlCommand("select FileData.FileName, FileExtension, FileData, FileDate from UserData inner join FileData on FileData.UserID = UserData.UserID where UserData.UserID = '" + (int)TempData["UserID"] + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(command);
        da.Fill(dtData);
        con.Close();
        return dtData;
    }

    public ActionResult DownloadFile(string FilePath)
    {
        string FileName = Server.MapPath("~" + FilePath);
        byte[] FileData = GetFile(FileName);
        return File(FileData, System.Net.Mime.MediaTypeNames.Application.Octet, FilePath);
    }

    byte[] GetFile(string s)
    {
        System.IO.FileStream fs = System.IO.File.OpenRead(s);
        byte[] data = new byte[fs.Length];
        int br = fs.Read(data, 0, data.Length);
        if (br != fs.Length)
        {
            throw new System.IO.IOException(s);
        }
        return data;
    }

用户数据类模型

public class UserDataClass
{
    public int UserID { get; set; }
    [Display(Name = "Имя")]
    [Required(ErrorMessage = "Введите имя пользователя")]
    public string UserName { get; set; }
    [Display(Name = "Email")]
    [Required(ErrorMessage = "Введите Email")]
    public string UserEmail { get; set; }
    [Display(Name = "Пароль")]
    [Required(ErrorMessage = "Введите пароль")]
    public string UserPassword { get; set; }
    [Display(Name = "Подтверждение пароля")]
    [Required(ErrorMessage = "Подтвердите пароль")]
    public string ConfirmPassword { get; set; }
    [Display(Name = "Выберите изображение")]
    public byte[] AvatarData { get; set; }
    public HttpPostedFileBase ImageFile { get; set; } //??? Может это лишнее
}

WorkSpaceClass 模型

public class WorkSpaceClass
{
    public string FileName { get; set; }
    public byte[] FileData { get; set; }
    public string FileExtension { get; set; }
    public string FileDate { get; set; }
    public int UserID { get; set; }
    
    public string FileURL { get; set; }
    public IEnumerable<WorkSpaceClass> FileList { get; set; }
}

【问题讨论】:

  • 问题的根源似乎在于您创建了自己的身份验证/授权系统。而你创建的那个是非常不安全的,因为它容易受到 SQL 注入并且使用纯文本密码。 ASP.NET MVC 框架已经内置了身份验证和授权,您应该真正使用它。 (在 ASP.NET MVC 中查找有关身份验证的教程。)当您使用框架提供的工具时,您不需要传递此电子邮件值。登录后,每个控制器操作都可以访问用户信息。
  • 我同意@David 所说的,使用 ASP.NET Identity 对您来说会更好、更容易。
  • 如果你必须使用这个代码,你能澄清你在哪里打电话UploadFile
  • @David 据我所知,ASP .NET 身份中的用户身份验证系统使用实体框架?这是在MVC框架中使用认证系统的唯一方法吗?
  • @MikhailKurakhtanov:实体框架是一种数据访问工具,而不是身份验证/授权工具。您可能正在考虑身份框架。

标签: c# asp.net asp.net-mvc


【解决方案1】:

根据我的理解,您的FileManager 操作比one argument 多,而您仅从login 操作方法传递one argument。你的操作方法是

public ActionResult FileManager(WorkSpaceClass wsc, string useremail)

你只通过useremail而不是WorkSpaceClass

return RedirectToAction("FileManager", "WorkSpace", new { useremail = log.UserEmail.ToString()});

分辨率 所以尝试将WorkSpaceClass 对象也从Login Action 方法传递给FileManager action 方法,就像这样。

return RedirectToAction("FileManager", "WorkSpace", new { wsc=new WorkSpaceClass(), useremail = log.UserEmail.ToString()});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多