ASP.NET MVC 使用code-first身份验证页面,无法上传文件。
创始人
2024-09-16 13:00:55
0

要在ASP.NET MVC中使用Code-First身份验证页面并允许文件上传,你需要做以下几个步骤:

  1. 创建一个新的ASP.NET MVC项目,使用Code-First身份验证模板。

  2. 添加必要的NuGet包。打开NuGet包管理器控制台,运行以下命令:

Install-Package Microsoft.AspNet.Identity.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.Owin.Security.Cookies
  1. 在IdentityModels.cs文件中,找到ApplicationUser类并添加一个新的属性来保存上传的文件路径。例如:
public class ApplicationUser : IdentityUser
{
    public string ProfilePicturePath { get; set; }
}
  1. 在ApplicationDbContext.cs文件中,找到OnModelCreating方法,并将以下代码添加到方法的底部:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity().ToTable("AspNetUsers").Property(p => p.ProfilePicturePath).HasMaxLength(255);
}
  1. 在RegisterViewModel.cs文件中,添加一个新的属性来接收上传的文件。例如:
public class RegisterViewModel
{
    // other properties

    [Required]
    [DataType(DataType.Upload)]
    public HttpPostedFileBase ProfilePicture { get; set; }
}
  1. 在AccountController.cs文件的Register方法中,将文件保存到服务器上的文件夹中,并将文件路径保存到ProfilePicturePath属性中。例如:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        // other code

        if (model.ProfilePicture != null && model.ProfilePicture.ContentLength > 0)
        {
            var fileName = Path.GetFileName(model.ProfilePicture.FileName);
            var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
            model.ProfilePicture.SaveAs(path);

            user.ProfilePicturePath = "/Uploads/" + fileName;
        }

        // other code
    }

    // other code
}
  1. 在Register.cshtml文件中,添加一个文件输入字段来允许用户上传文件。例如:
@Html.LabelFor(model => model.ProfilePicture, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.ValidationMessageFor(model => model.ProfilePicture, "", new { @class = "text-danger" })

这样,你就可以在ASP.NET MVC中使用Code-First身份验证页面并允许文件上传了。请注意,上述代码仅为示例,你可能需要根据你的具体需求进行修改。

相关内容

热门资讯

推荐十款“wepoker好牌率... >>您好:wepoker好牌率确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好,总是...
开挂辅助插件"aap... 开挂辅助插件"aapoker脚本"开挂(透视)辅助安装(有挂详情) 了解更多开挂安装加(136704...
一秒答解“wepoker微透视... 一秒答解“wepoker微透视挂方法”开挂辅助工具(透视)2026新版是一款可以让一直输的玩家,快速...
开挂辅助安装"聚星a... 开挂辅助安装"聚星ai辅助工具收费多少"开挂(透视)辅助脚本(有挂神器);AI辅助机器人普及解说快速...
专业讨论“wepoker辅助器... >>您好:wepoker辅助器透视挂确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
开挂辅助插件"约局吧... 【亲,约局吧如何查看是否有挂 这款游戏可以开挂的,确实是有挂的,很多玩家在这款约局吧如何查看是否有挂...
玩家必备攻略“微乐扑克记牌器怎... 微乐扑克记牌器怎么用是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加...
开挂辅助软件"wep... 【亲,wepoker辅助辅助 这款游戏可以开挂的,确实是有挂的,很多玩家在这款wepoker辅助辅助...
盘点一款“wepoker辅助挂... >>您好:wepoker辅助挂怎么用最安全确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
开挂辅助平台"wep... 开挂辅助平台"wepoker有机器人吗"开挂(透视)辅助安装(有挂方法)您好:wepoker有机器人...