asp.net-mvc ASP.NET MVC 唯一性验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4298835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:36:34  来源:igfitidea点击:

ASP.NET MVC validation of uniqueness

asp.net-mvcvalidationunique

提问by Alex

Rails has a very convenient uniqueness validation.

Rails 有一个非常方便的唯一性验证。

ASP.NET MVC doesn't.

ASP.NET MVC 没有。

I need to make sure that the e-mail address a user has entered hasn't been registered by anyone yet.

我需要确保用户输入的电子邮件地址尚未被任何人注册。

I can see only one way of doing this kind of validation: create a new data context object in the UniqueAttribute class.

我只能看到进行这种验证的一种方法:在 UniqueAttribute 类中创建一个新的数据上下文对象。

But I'm afraid that wasting memory on a new data context object just for one validation is dangerous.

但是我担心仅仅为了一次验证而在新的数据上下文对象上浪费内存是危险的。

Am I wrong? Is there a better way to do that?

我错了吗?有没有更好的方法来做到这一点?

Update

更新

This is what I got so far

这是我到目前为止所得到的

public class UniqueEmailAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        DataContext db = new DataContext();
        var userWithTheSameEmail = db.Users.SingleOrDefault(
            u => u.Email == (string)value);
        return userWithTheSameEmail == null;
    }
}

// Usage
[UniqueEmail(ErrorMessage="This e-mail is already registered")]
public string Email { get; set; }

There are two problems.

有两个问题。

  1. It would be good to have just one UniqueAttribute class, not separate classes for e-mails, usernames etc. How can I do that?

  2. Creating a newdata context every time you need to validate a single attribute.

  1. 最好只有一个 UniqueAttribute 类,而不是用于电子邮件、用户名等的单独类。我该怎么做?

  2. 每次需要验证单个属性时都会创建一个新的数据上下文。

SOLUTION

解决方案

So in the end I created a unique constraint on the table and now I just have to intercept SqlException in Users repository. Works great and is probably more efficient than searching for the same node in the whole table. Thanks!

所以最后我在表上创建了一个唯一的约束,现在我只需要拦截用户存储库中的 SqlException 。效果很好,并且可能比在整个表中搜索相同节点更有效。谢谢!

采纳答案by Dmitry S.

A foolproof way of doing this is to create a validation attribute that would query the database for the email address. It would certainly add latency.

一种万无一失的方法是创建一个验证属性,该属性将在数据库中查询电子邮件地址。它肯定会增加延迟。

An alternative would be to create a unique constraint on the table and intercept SqlException.

另一种方法是在表上创建唯一约束并拦截 SqlException。

回答by swapneel

Mvc 3 Relaease candidate has new New Validation Attributes as a remotevalidation -where you can register a method for validation on clientside(jquery).

Mvc 3 Relaease 候选具有新的新验证属性作为远程验证 - 您可以在其中注册客户端验证方法(jquery)。

see below example- RemoteAttribute

见下面的例子- RemoteAttribute

The new RemoteAttribute validation attribute takes advantage of the jQuery Validation plug-in's remote validator, which enables client-side validation to call a method on the server that performs the actual validation logic.

新的 RemoteAttribute 验证属性利用了 jQuery 验证插件的远程验证器,它使客户端验证能够调用服务器上执行实际验证逻辑的方法。

In the following example, the UserName property has the RemoteAttribute applied. When editing this property in an Edit view, client validation will call an action named UserNameAvailable on the UsersController class in order to validate this field.

在以下示例中,UserName 属性应用了 RemoteAttribute。在 Edit 视图中编辑此属性时,客户端验证将调用 UsersController 类上名为 UserNameAvailable 的操作以验证此字段。

public class User {  
    [Remote("UserNameAvailable", "Users")]  
    public string UserName { get; set; }  
}  

The following example shows the corresponding controller.

以下示例显示了相应的控制器。

public class UsersController {  
        public bool UserNameAvailable(string username) {  
            return !MyRepository.UserNameExists(username);  

       }  
   }

Mvc 3

MVC 3

UPDATE

更新

    public bool UserNameAvailable(string Propertyname)  
    {  
        if (Request.QueryString[0]= "UserName")  
        {   
            //validate username  
        }  
        elseif (Request.QueryString[0]= "Email")  
        {  
            //Validate Email  
        }  

    }   

回答by Kila Morton

ASP.Net does have a feature that can automatically check the uniqueness of a user's email address when a user registers. It is the ASP.Net Membership service and you can use it to do what you want even if you don't use all of the features of it.

ASP.Net 确实有一项功能,可以在用户注册时自动检查用户电子邮件地址的唯一性。它是 ASP.Net Membership 服务,即使您不使用它的所有功能,您也可以使用它来做您想做的事情。

If you are not using the full Membership feature in your MVC application, then all you need to do is use

如果您没有在 MVC 应用程序中使用完整的 Membership 功能,那么您需要做的就是使用

Membership.FindUsersByEmail(emailYouAreLookingFor);

Membership.FindUsersByEmail(emailYouAreLookingFor);

If any values come back, you know that the address is not unique. If you ARE using the Membership service to create users, then the Membership service will check AUTOMATICALLY and return a code to you if the user's email address is not unique.

如果返回任何值,您就知道该地址不是唯一的。如果您使用会员服务来创建用户,则会员服务将自动检查并在用户的电子邮件地址不唯一时向您返回代码。

The Membership service sits in the System.Web.Security area so you would need a

Membership 服务位于 System.Web.Security 区域中,因此您需要一个

using System.Web.Security;

使用 System.Web.Security;

reference in your controller.

在您的控制器中引用。

Here is an example

这是一个例子

            MembershipCreateStatus createStatus = MembershipService.CreateUser(UserName, Password, Email);

            if (createStatus == MembershipCreateStatus.DuplicateEmail)
            {

                   //do something here
            }
            else
            {
                   //do something here

            }
            MembershipCreateStatus createStatus = MembershipService.CreateUser(UserName, Password, Email);

            if (createStatus == MembershipCreateStatus.DuplicateEmail)
            {

                   //do something here
            }
            else
            {
                   //do something here

            }

I hope this helps!

我希望这有帮助!

回答by RickAndMSFT

The right way to make a generic remote unique validator in MVC can be found in this MVC forum.by counsellorben. It's based on my MVC unique remote validator article http://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx

MVC 论坛中可以找到在MVC 中制作通用远程唯一验证器的正确方法通过辅导员本。它基于我的 MVC 独特的远程验证器文章http://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx