简体   繁体   中英

How to make a property required on POST but not on PUT requests

Let's say I have an User model which has Email and Password properties for authentication purposes, as follows:

public class User
{
    public long Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

My goal is to make these properties required only on POST requests, but not on PUT. That is: Email and Password fields are required to create a new user. But when editing I can omit these properties. I know that this goal can be archived removing the [Required] from Email and Password and checking for these properties when POSTing, but this does not seem to be a good practice.

So, there is a more elegant solution for this use case?

You shouldn't use an Entity as input/output parameters. Instead, create two separate view models that represent the actions being called:

public class User
{
    public long Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

// When creating, the client cannot know the Id because it doesn't exist
public class CreateUserViewModel
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

// and when updating, the Id is required but not the Email nor the Password
public class UpdateUserViewModel
{
    [Required]
    public long Id { get; set; } 

    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
}

Of course, since you are creating an API, "View Model" might not make a lot of sense. You may use the Data Transfer Object (DTO) term instead.

One suggestion would be to use View Models. In your case, you could have a RegisterViewModel that takes all of the values from the model and then you could have an EditViewModel that doesnt include email and password. In your controller, your edit function can either replace the old values for the other field or just ignore them.

https://www.codeproject.com/Articles/1174826/Using-MVVM-in-MVC-Applications-Part

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM