我正在根据用户名进行身份验证。因此,未经授权的人无法看到任何正常工作的方法。
问题是所有用户都能够彼此数据。 A人不应该看到B人的记录,这样他/她就无法编辑他人的记录。有谁知道我怎么能为此写一个lambda表达式? 我在下面粘贴了我的编辑方法:
// GET: /IcerikDB_/Edit/5
[Authorize(Roles = "Administrator")]
public ActionResult Edit(int id)
{
icerik icerik = db.icerik.Find(id);
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
[HttpPost]
public ActionResult Edit(icerik icerik)
{
if (ModelState.IsValid)
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
icerik.Userid = user.UserId;
db.Entry(icerik).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
以下是icerik.cs的代码
namespace KategoriEditor.Icerik_DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class icerik
{
public int Id { get; set; }
public Nullable<int> Kategorid { get; set; }
public Nullable<System.Guid> Userid { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Baslangic { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Bitis { get; set; }
public string tamicerik { get; set; }
public string kisaicerik { get; set; }
public string resimlink { get; set; }
public virtual Kategoriler Kategoriler { get; set; }
public virtual Users Users { get; set; }
}
}
答案 0 :(得分:1)
试试这个:
public ActionResult Edit(int id)
{
// Get the currently logged in user.
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
// Determine whether the requested id is the same id as the currently logged in user.
icerik icerik = db.icerik.Find(id);
if (icerik.Userid.HasValue && icerik.Userid.Value == user.UserId)
{
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
// You should not need this SelectList anymore.
//ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
// This redirect the unauthorized user to the homepage. This can be any other page of course.
return RedirectToAction("Index", "Home");
}