C# 我应该先检查身份验证还是检查ModelState.IsValid
我有一个.NET MVC5网站,用户使用Microsoft身份登录。我有多个表单帖子,用于在整个站点中添加和编辑项目。我想知道我应该按哪个顺序执行验证:-C# 我应该先检查身份验证还是检查ModelState.IsValid,c#,.net,asp.net-mvc,asp.net-identity,modelstate,C#,.net,Asp.net Mvc,Asp.net Identity,Modelstate,我有一个.NET MVC5网站,用户使用Microsoft身份登录。我有多个表单帖子,用于在整个站点中添加和编辑项目。我想知道我应该按哪个顺序执行验证:- ModelState.IsValid,然后User.Identity.IsAuthenticated User.Identity.isAuthentication然后ModelState.IsValid 我现在有下面的代码可以运行,但似乎是“鸡和蛋”的例子:- var user = UserAccountFunctions.GetUser
- ModelState.IsValid,然后User.Identity.IsAuthenticated
- User.Identity.isAuthentication然后ModelState.IsValid
var user = UserAccountFunctions.GetUser(User);
if (user != null)
{
ClientProfile profile = ClientProfile.GetUser(user.Id, db);
if (profile != null)
{
if (ModelState.IsValid)
{
// Do logic here
}
}
}
在检查身份验证之前,是否应先交换此代码以检查模型,以便:-
if (ModelState.IsValid)
{
var user = UserAccountFunctions.GetUser(User);
if (user != null)
{
ClientProfile profile = ClientProfile.GetUser(user.Id, db);
if (profile != null)
{
// Do logic here...
}
}
}
还是这里根本没有区别?我在整个网站上重复了很多这段代码,那么寻找哪一个是更好的选择呢?我目前使用最上面的一个,因为我觉得你甚至不应该尝试检查模型,除非它们经过身份验证
有什么建议吗
谢谢 以下是更新用户电子邮件的示例:
[AcceptVerbs(HttpVerbs.Post)]
[Authorize]
[ValidateAntiForgeryToken()]
public ActionResult emailupdate(UserEmailEditModel editmodel_post)
{
if (!ModelState.IsValid)
{
// redirect to email view and show errors
}
// check if posted id is the same as stored in session
if (User.Identity.GetUserId() != editmodel_post.user_id.ToString())
{
// redirect to email view and show errors
}
}
所以
首先进行身份验证,您可以通过向方法(或控制器)添加
[Authorize]
属性来进行身份验证。请使用Authorize属性,如Stephen所述。验证在授权后进行,因为您不希望经过授权的用户查看模型是否无效[Authorize]是否与(User.Identity.IsAuthenticated)相同?如果是的话,那太好了!