如何将 ASP.NET Core 身份链接到另一个实体?

时间:2021-01-18 02:18:47

标签: c# asp.net-core entity-framework-core asp.net-core-mvc asp.net-identity

伙计们,我想创建一个简单的应用程序,用户可以在其中发布他们想要的任何文本,带有标题和正文的内容。问题是我想通过身份验证将其设为私有,以便我只能看到我使用电子邮件和密码发布的帖子,以实现我计划使用身份验证的身份验证。

这是我想代表的模型:

enter image description here

我尝试在 C# 代码中执行此操作并得到以下结果: enter image description here

那个模型代码适合我想做的事情吗?

这是我的 ApplicationDbContext:

enter image description here

如果没有那么大的努力,我想要一个示例,为登录用户创建一个新帖子,然后显示该用户发布的帖子。

谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个完整的工作演示,您可以参考:

型号:

public class User:IdentityUser
{
    public List<Post> Posts { get; set; }
}
public class Post
{
    [Key]
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    [ForeignKey("User")]
    [MaxLength(450)]
    public string UserId { get; set; }
    public User User { get; set; }
}

Index.cshtml:

@model IEnumerable<Post>
<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Title)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Body)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.User)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Body)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.User.Id)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.PostId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.PostId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.PostId">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

创建.cshtml:

@model Post

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Post</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Body" class="control-label"></label>
                <input asp-for="Body" class="form-control" />
                <span asp-validation-for="Body" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

控制器:

public class PostsController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly UserManager<User> _userManager;
    public PostsController(ApplicationDbContext context,UserManager<User> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    // GET: Posts
    public async Task<IActionResult> Index()
    {
        var applicationDbContext = _context.Posts.Include(p => p.User)
                                                .Where(a=>a.User.UserName==User.Identity.Name);
        return View(await applicationDbContext.ToListAsync());
    }
    // GET: Posts/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Posts/Create
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Post post)
    {
        var user = _userManager.FindByNameAsync(User.Identity.Name).Result;
        post.UserId = user.Id;
        if (ModelState.IsValid)
        {
            _context.Add(post);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(post);
    }
}

请务必更新您的 _LoginPartial.cshtml:

@using Microsoft.AspNetCore.Identity
@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager

请务必更新您的 Startup.cs:

services.AddDefaultIdentity<User>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

结果:

enter image description here