Authentication 如何只允许;拥有;要编辑它的数据?

Authentication 如何只允许;拥有;要编辑它的数据?,authentication,asp.net-mvc-3,Authentication,Asp.net Mvc 3,我知道如何使用注释仅允许授权用户或某些角色的用户,但如何仅允许拥有数据的个人对其进行编辑 如果我有用户foo和用户bar。Foo可以转到localhost/User/Edit/Foo并输入他的详细信息。如何防止Foo转到localhost/User/Edit/Bar并编辑Bar信息?如果您试图编辑非您的配置文件,堆栈溢出将为您提供一个未找到的页面。这是如何做到的?您的控制器都可以访问User.Identity对象(http://msdn.microsoft.com/en-us/library/s

我知道如何使用注释仅允许授权用户或某些角色的用户,但如何仅允许拥有数据的个人对其进行编辑


如果我有用户foo和用户bar。Foo可以转到
localhost/User/Edit/Foo
并输入他的详细信息。如何防止Foo转到
localhost/User/Edit/Bar
并编辑Bar信息?如果您试图编辑非您的配置文件,堆栈溢出将为您提供一个未找到的页面。这是如何做到的?

您的控制器都可以访问User.Identity对象(http://msdn.microsoft.com/en-us/library/system.web.httpcontext.user.aspx)

您可以使用此信息确定当前经过身份验证的用户。然后,您可以检查用户是否具有以下权限:

public ActionResult Foo(int id)
{
    if (DatabaseService.DoesUserHavePermission(User.Identity.Name, id) == false)
        return View("ErrorPage");

    return View("SuccessPage", yourdata);
}
或者,您可以使用只返回当前经过身份验证的用户的数据的方法:

public ActionResult Foo(int id)
{
    var data = DatabaseService.GetDataForUser(User.Identity.Name);

    return View(data);
}

再加上我的两分钱,因为您使用的是ASP.NET MVC 3,所以可以使用新的
HttpNotFoundResult
如下:

return new HttpNotFoundResult();

//Or using the shorthand method
return HttpNotFound();
如果您想要的是
404
重定向,请不要使用
返回视图(“ErrorPage”)