ASP.NET Identity通过UserId

时间:2016-05-08 13:56:11

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

在我的ASP.NET MVC应用程序中,用户可以发布项目,并将它们存储在数据库中。像往常一样,项目的索引视图中用户可以看到所有可用项目的列表,以及旁边的一些操作链接(详细信息/应用)。
当用户点击"应用"动作链接,他被要求填写一些关于他想参加的原因(求职信)。在他提交之后,应用程序存储在数据库中,其中包含一个唯一的ApplicationId,用户的UserId和他正在申请的ProjectId,因此我可以跟踪所有申请。

public class Application
{
    public int ApplicationId { get; set; }
    public int ProjectId { get; set; }
    public string UserId { get; set; }
    public string CoverLetter { get; set; }
}

在"细节"查看,正在显示所有项目的数据,并设法使其显示所有申请该项目的求职信和用户标识。

Cover letters:
@foreach (var item in Model.Applications)
{
    <tr>
        <td>
            <br/>
            @Html.DisplayFor(modelItem => item.CoverLetter) |
            @Html.DisplayFor(modelItem => item.UserId) |
        </td>
    </tr>
}

应用程序中的UserIdCoverLetter已成功检索,但我需要的是基于UserId从数据库中检索用户的名称和电子邮件。

编辑:这是整个ProjectsController:

   using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.Security;
using Leepio.Models;
using Microsoft.ApplicationInsights.Web;
using Microsoft.AspNet.Identity;

namespace Leepio.Controllers
{
    public class ProjectsController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Projects
        [Authorize(Roles = "companyRole, studentRole")]
        public ActionResult Index(string SortOrder, string SortBy, string Page)
        {
            ViewBag.SortOrder = SortOrder;
            ViewBag.SortBy = SortBy;
            var projects = db.Projects.ToList();




            var model = new ApplicationTwoViewModel
            {
                Model1 = new List<Project>(projects),
                Model2 = new Application
                {

                    UserId = User.Identity.GetUserId(),
                    ProjectId = 11,
                    CoverLetter = "asdf",
                    ApplicationId = 23,
                }
            };

            switch (SortBy)
            {
                case "Title":
                 switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.Title).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.Title).ToList();
                            break;
                        default:
                            break;
                    }
                    break;

                case "ApplicationDeadline":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.ApplicationDeadline).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.ApplicationDeadline).ToList();
                            break;
                        default:
                            break;
                    }
                    break;

                case "Duration":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.Duration).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.Duration).ToList();
                            break;
                        default:
                            break;
                    }
                    break;
                case "HourlyRate":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.HourlyRate).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.HourlyRate).ToList();
                            break;
                        default:
                            break;
                    }
                    break;
                case "TotalProjectCost":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.TotalProjectCost).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.TotalProjectCost).ToList();
                            break;
                        default:
                            break;
                    }
                    break;
                case "City":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.City).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.City).ToList();
                            break;
                        default:
                            break;
                    }
                    break;
                case "RequiredPresencePercent":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.RequiredPresencePercent).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.RequiredPresencePercent).ToList();
                            break;
                        default:
                            break;
                    }
                    break;
                case "Language":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.Language).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.Language).ToList();
                            break;
                        default:
                            break;
                    }
                    break;
                case "RequiredSkills":
                    switch (SortOrder)
                    {
                        case "Asc":
                            projects = projects.OrderBy(x => x.RequiredSkills).ToList();
                            break;
                        case "Desc":
                            projects = projects.OrderByDescending(x => x.RequiredSkills).ToList();
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    projects = projects.OrderBy(x => x.Title).ToList();
                    break;
            }



            ViewBag.TotalPages = Math.Ceiling(db.Projects.ToList().Count()/10.0);
            int page = int.Parse(Page == null ? "1" : Page);
            ViewBag.Page = page;
            model.Model1 = projects;    
            model.Model1 = model.Model1.Skip((page - 1) * 10).Take(10).ToList();
            return View(model);

        }



        private UserManager<IUser<>  userManager;


        // GET: Projects/Details/5
        [Authorize(Roles = "companyRole, studentRole")]
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Project project = db.Projects.Find(id);

            if (project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        // GET: Projects/Create
        [Authorize(Roles= "companyRole")]
        public ActionResult Create()
        {
            return View();
        }

        // POST: Projects/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "companyRole")]
        public ActionResult Create([Bind(Include = "UserId,ProjectId,Title,ApplicationDeadline,Duration,HourlyRate,TotalProjectCost,City,RequiredPresencePercent,Language,RequiredSkills,Description")] Project project)
        {
            if (ModelState.IsValid)
            {
                project.UserId = User.Identity.GetUserId();
                db.Projects.Add(project);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(project);
        }

        // GET: Projectts/Edit/5
        [Authorize(Roles = "companyRole")]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        // POST: Projects/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "companyRole")]
        public ActionResult Edit([Bind(Include = "ProjectId,UserId,Title,ApplicationDeadline,Duration,HourlyRate,TotalProjectCost,City,RequiredPresencePercent,Language,RequiredSkills,Description")] Project project)
        {
            if (ModelState.IsValid)
            {

                if (project.UserId == User.Identity.GetUserId())
                { 
                db.Entry(project).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
                }

                return HttpNotFound("Project is not yours!");

            }
            return View(project);
        }

        // GET: Projects/Delete/5
        [Authorize(Roles = "companyRole")]
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        // POST: Projects/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "companyRole")]
        public ActionResult DeleteConfirmed(int id)
        {
            Project project = db.Projects.Find(id);
            if (project.UserId == User.Identity.GetUserId())
            {
                db.Projects.Remove(project);
                db.SaveChanges();
            }
            else
            {
                return HttpNotFound("Project is not yours!");
            }


            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

我是否真的需要更改ApplicationController内的任何内容?我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

您可能无需修改ApplicationController。找到Project后,使用Project.UserId从Identity框架中获取关联的User,例如... UserManager.FindByIdAsync(userId)

您需要修改已退回的模型以将该信息传递回您的视图,但可以实现您的请求。

鉴于您当前的Application课程,您可以从头开始或通过继承创建新模型,添加视图所需的属性...

public class ProjectDetailsApplicationModel : Application {
    public string UserName { get; set; }
    public string Email { get; set; }
}

......上面通过继承显示了模型。

然后,您可以为视图创建一个视图模型,其中包含显示所需详细信息所需的所有信息...

public class ProjectDetailsModel {
    public Project Project { get; set; }
    public IEnumerable<ProjectDetailsApplicationModel> Applications { get; set; }
}

现在您表示您正在使用Asp.Net-Identity框架,因此假设您的ProjectsController可以修改为类似的内容......

public class ProjectsController : Controller {
    private ApplicationDbContext db;
    private ApplicationUserManager userManager;

    public ProjectController() {
        this.userManager =  new ApplicationUserManager();
        this.db = new ApplicationDbContext();
    }

    //...other code removed for brevity

    public async Task<ActionResult> Details(int? id) {
        if (id == null) {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Project project = db.Projects.Find(id);

        if (project == null) {
            return HttpNotFound();
        }
        //construct model...                    
        var model = new ProjectDetailsViewModel {
            Project = project,
            Applications = await BuildApplicationModels(project.Applications)
        }

        return View(model);
    }
    private async Task<IEnumerable<ProjectDetailsApplicationModel>> BuildApplicationModels(IEnumerable<Application> applications) {
        List<ProjectDetailsApplicationModel> result = new List<ProjectDetailsApplicationModel>();
        foreach (var application in applications) {
            var model = new ProjectDetailsApplicationModel {
                ApplicationId = application.ApplicationId,
                ProjectId = application.ProjectId,
                UserId = application.UserId,
                CoverLetter = application.CoverLetter
            };

            var user = await userManager.FindByIdAsync(application.UserId);
            if (user != null) {
                model.UserName = user.UserName;
                model.Email = user.Email;
            }
            result.Add(model);
        }
        return result;
    }
}

然后,您可以在视图中引用用户的姓名和电子邮件...

@model: ProjectDetailsModel

<!--...other markup...-->

Cover letters:
@foreach (var item in Model.Applications)
{
    <tr>
        <td>
            <br/>
            @Html.DisplayFor(modelItem => item.CoverLetter) |
            @Html.DisplayFor(modelItem => item.UserName) |
            @Html.DisplayFor(modelItem => item.Email) |
        </td>
    </tr>
}

答案 1 :(得分:0)

我找到了解决方案,简单得多。

在ProjectsController内部详细说明GET方法:

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    Project project = db.Projects.Find(id);
    var user = UserManager.FindByIdAsync(project.UserId);
    ViewData["user"] = user.Result.Email;

    if (project == null)
    {
        return HttpNotFound();
    }
    return View(project);
}

基本上检索'user'var中的整个User实体。 然后我用ViewData [“user”] = user.Result.Email发送它到视图;

@foreach (var item in Model.Applications)
{
    <tr>
        <td>
            <br />
            @Html.DisplayFor(modelItem => item.CoverLetter) |
            @Html.DisplayFor(modelItem => @ViewData["user"])
        </td>
    </tr>
}

我将UserManager初始化为:

private ApplicationDbContext db = new ApplicationDbContext();

public ProjectsController()
    : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{

}

public ProjectsController(UserManager<ApplicationUser> userManager)
{
    UserManager = userManager;
}

public UserManager<ApplicationUser> UserManager { get; set; }