简体   繁体   中英

How to restrict some properties to modified from Web API in .net core?

I am working on .net core Web API project. I have two classes:

public class CategoryMasterDto : CommonInfoDto
{
    public int CategoryId { get; set; }
    [StringLength(50)]
    public string CategoryName { get; set; }
    public string CategoryImage { get; set; }
}

public class CommonInfoDto
{
    public Guid CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public Guid ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
    public short Status { get; set; }
}

Now, I want to restrict users to specify values for certain properties from Web API like CategoryId and all properties of CommonInfoDto as I will specify all these properties from my side before inserting data in the database.

I tried using JsonIgnore using which properties will not be visible in the tools like swagger. But again if the user manually specified those properties, the values will be received on the server-side.

For eg if I apply JsonIgnore to CategoryId, it will no be visible in swagger but if the user adds the property CategoryId and pass some value, it will be received on the server-side.

I want to achieve two things:

  1. Restrict the users to pass values for certain properties or even if it is passed, those should not be bind to the properties on the server-side during the POST and PUT request.

  2. I want to pass all properties when user requests for GET request.

I already have one solution ie to create one DTO for GET and another for POST/PUT. Is there any better solution through which I can use the same DTO for both and achieve what I want.?

You need just one DTO class for GET, POST/PUT. And, you could use AutoMapper tool to configure mapping from model domain class to DTO class, and back. And then, while configuring mapping from DTO to domain model class, you could ignore certain parameters.

CreateMap<CommonInfoDto, CommonInfo>().ForMember(x => x.Guid, opt => opt.Ignore());

It means that you would read data from database (your domain model class), pass it to DTO class with all the parameters; but when you would recieve data from from user (DTO class), while saving you will not use its Guid (because it will be ignored during mapping).

As what everybody is suggesting. This can only be Achieve using 2 classes. Input.Model and Domain.Model, then use Automapper to automatically map properties to your actual Domain.Model during input process (POST/PUT) while you return you Domain.Model in your GET endpoints.

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