简体   繁体   中英

How to make optional Model Class Properties in Asp.Net Web Api

I have a model class looks like,

     public string EmpID { get; set; }
     public string Mobile { get; set; }
     public string Email { get; set; }
     public string OfficeAddress { get; set; }
     public string City { get; set; }
     public string State { get; set; }

But In my Api response i want to send based on condition, if condition 1 satisfy then send below response,

{
     "EmpID":"1",
     "Email":"abc@gmail.com"
}

if condition 2 satisfy then send below response,

{
     "EmpID":"1",
     "Mobile":"1234567890"
     "Email":"abc@gmail.com"
}
else
{
     //send full model class property
}

//Note: I used JsonIgnore property in model class. But its not work in my case. Is there any way to Ignore Property in controller or bussiness logic layer?

From your example, it's looking like you want to include a property based on a condition. If I remember correctly, JSON will just not include the property in the response if the value is null. However, a doc generator like Swagger might still include the property, to prevent a client from getting incomplete data objects. I am not 100% on this though.

That said, depending on how you define the response, your code should do fine as-is.

What you could try is define a separate response model, in which you define the Mobile property as nullable, as well as any other properties that might be null. Then in your controller, you map the business model to your response model through manual initialization or using AutoMapper and return that. Your code would look something like below:

public async Task<ActionResult<ResponseModel>> GetResponseModel()
{
    var businessModel = await businessManager.GetBusinessModel();

    if (<condition1>) {
        return new ResponseModel
        {
            EmpId = businessModel.EmpId,
            Email = businessModel.Email
        };
    } else if (<condition2>) {
        return new ResponseModel
        {
            EmpId = businessModel.EmpId,
            Mobile = businessModel.Mobile,
            Email = businessModel.Email
        };
    } else {
        // return full BusinessModel as ResponseModel
    }
}

If using AutoMapper, you would replace new ResponseModel {...} with AutoMapperField.Map<ResponseModel>(businessModel) .

[JsonIgnore] instructs a (De-)Serializer to ignore a property when serializing or deserializing to JSON, but as far as I am aware .NET ignores these in API responses in favour of being RESTful.

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