要在ASP.NET MVC中使用Code-First身份验证页面并允许文件上传,你需要做以下几个步骤:
创建一个新的ASP.NET MVC项目,使用Code-First身份验证模板。
添加必要的NuGet包。打开NuGet包管理器控制台,运行以下命令:
Install-Package Microsoft.AspNet.Identity.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.Owin.Security.Cookies
ApplicationUser
类并添加一个新的属性来保存上传的文件路径。例如:public class ApplicationUser : IdentityUser
{
public string ProfilePicturePath { get; set; }
}
OnModelCreating
方法,并将以下代码添加到方法的底部:protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity().ToTable("AspNetUsers").Property(p => p.ProfilePicturePath).HasMaxLength(255);
}
public class RegisterViewModel
{
// other properties
[Required]
[DataType(DataType.Upload)]
public HttpPostedFileBase ProfilePicture { get; set; }
}
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
}
@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身份验证页面并允许文件上传了。请注意,上述代码仅为示例,你可能需要根据你的具体需求进行修改。