"The JSON value could not be converted to Enum in Refit

Viewed 3687

I have one .Net Core Razor pages app which is trying to call a .Net Core API with a class library created using Refit.

I have created one Refit API interface which uses a model with enum as one of the property type.

Here is the interface snippet on the API side: IPaymentAPI interface

    [Post("/recharge")]
    Task<string> Recharge([Body] RechargeRequest request);

Here is the request model: The model contains one simple enum ELicenseType.

public class RechargeRequest
{
    public ELicenseType LicenseType{ get; set; }
}

The ELicenseType:

public enum ELicenseType
{
    NotSpecified = 0,
    Standard = 1,
    Commercial = 2
}

The API implementation in controller:

    [HttpPost("recharge")]
    public async Task<IActionResult> Recharge(
        [FromBody] RechargeRequest request)
    {
        Recharge result = await _mediator.Send(_mapper.Map<RechargeCommand>(request));

        return Ok();
    }

When calling this Recharge method the Refit is throwing the ValidationApiException:

ValidationApiException: Response status code does not indicate success: 400 (Bad Request).

And the content is:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-f9178d81421bca438241dd2def43d065-edbd7f210919b24e-00",
  "errors": {
    "$.licenseType": [
      "The JSON value could not be converted to ELicenseType. Path: $.licenseType | LineNumber: 0 | BytePositionInLine: 98."
    ]
  }
}

It seems that the Refit library does not support Enums in the request or my JSON serializer is misconfigured.

1 Answers

Do you need to set this config in your startup.cs?

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers().AddJsonOptions(opt =>
     {
         opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
     });
 }
Related