Home > Back-end >  How to make ASP.NET Core (v3.1) Web API accepts child class parameter from body
How to make ASP.NET Core (v3.1) Web API accepts child class parameter from body

Time:10-19

I am now making an API to accept third party token info and store it into DB. The class definition like:

public class ThirdPartyBaseToken
{
    [JsonProperty("accessToken")]
    public virtual string AccessToken { get; set; }

    [JsonProperty("brand")]
    public virtual string Brand { get; set; }
}

And the API in controller like:

public async Task<IActionResult> SaveTokenAsync([FromBody]ThirdPartyBaseToken tokenBody)
{
    var request = new SavingRequest
    {
        ThirdPartyToken = tokenBody.AccessToken,
        ……
        ……
    };
    
    await backendService.SaveAsync(request);

    return this.StatusCode(201);
}

However I met some exceptions and after I did the investigation, I found the property names from some third parties were "accessToken", but others were "openToken". In this case, I created a child class inherited from base class and override the JsonProperty like:

public class ThirdPartyChildToken: ThirdPartyBaseToken
{
    [JsonProperty("openToken")]
    public override string AccessToken { get; set; }
}

I hope once the "openToken" property comes, the API can accept it and get the token info from AccessToken correctly. Unfortunately, I debugged locally and I found the AccessToken was still null, which means the JsonProperty("openToken") did not work.

Could someone give me some instructions to resolve the problem?

CodePudding user response:

I feel like from a design standpoint, it would be best to keep the convention that the property names match the JSON property names. So, you could add both properties, and then check which one is not null.

public string GetToken()
    => this.AccessToken ?? this.OpenToken ?? throw new Exception("Token is null.");

This convention also has the advantage, that you don't have to specify every [JsonProperty] attribute explicitly.

  • Related