hanushic
hanushic

Reputation: 389

Issue when sending Json post request with Enums in ASP.NET Core

I am working on an ASP.NET Core 6.0 project. I tried to send a post request through the postman. But It hits the controller as a null value when My model has an enums data type.

I have a string enum

public enum TransactionType
{
    [StringValue("Payment")]
    Payment,

    [StringValue("Deferred")]
    Deferred,

    [StringValue("Refund")]
    Refund,

    [StringValue("Repeat")]
    Repeat,
}

And this is my request

{
  "transactionType": "Payment",  
   "amount": 1000
}

This is my controller

public async Task<IActionResult> Payment([FromBody] PaymentRequest paymentRequest)
{
    var result = await _opayoPaymentService.PaymentTranscation(paymentRequest);
        
    return Ok(result);
}

This is my model class:

public class PaymentRequest
{
     public TransactionType TransactionType { get; set; }  // If I comment this The request is hitting fine otherwise It hit as null value,
     public int Amount { get; set; }
}

I guess my enums are wrong. Could anyone help me to find the problem?

Upvotes: 2

Views: 3227

Answers (2)

Observer
Observer

Reputation: 130

D A response is correct. But if you want to be able to send the string value very easily, you just have to add:

[JsonConverter(typeof(StringEnumConverter))]
public enum TransactionType
{
...

From Newtonsoft.Json;

Upvotes: 1

D A
D A

Reputation: 2054

Your mapping in your controller will not be make on the StringValue meta but on the int type of the enum. And in your case Payment is 0, Deferred is 1 and so on. You can assign different values for them if you don't want to let the framework to do it automatically for you. So instead of

{ "transactionType": "Payment",
"amount": 1000 }

use

{ "transactionType": 0,
"amount": 1000 }

Upvotes: 2

Related Questions