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?
CodePudding user response:
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 }