Response "',' is an invalid start of a value. Path: $. in Asp.Net Core API

Viewed 18809

I am developing API in Asp.Net Core 3.1, I have a POST method below (content type is application/JSON), I am passing an invalid JSON to the response deliberately and response is also very clear. But here my question is can I make changes to return the response like

countryId is a required field

for this particular case. Please let me know if it can be done, otherwise, I am fine with this response also(because this response is also valid firs to check the content type is a valid JSON or not).

Method:

public ActionResult ValidateFields(ValidateFieldsRequest validateFieldsRequest)
        {

Request class:

public class ValidateFieldsRequest
{
    //string currencyCode, int countryId, string fieldName, string fieldValue

    [Required]
    public string currencyCode { get; set; }
    [Required]
    [RegularExpression("^[1-9]\\d*$", ErrorMessage = "Invalid fieldName.")]
    public int countryId { get; set; }
    [Required]
    [MinLength(1, ErrorMessage = "At least one field required")]
    public List<Field> fields { get; set; }

}

Request:

{
    "currencyCode": "RUB",
    "countryId": ,
    "fields": [{
            "fieldName": "BIC or Bank Code",
            "fieldValue": "12345678901234567"
        },
        {
            "fieldName": "Beneficiary Account Number",
            "fieldValue": "123456"
        }
    ]
}

Response:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|6a64d7ad-495850db788356cd.",
    "errors": {
        "$.countryId": [
            "',' is an invalid start of a value. Path: $.countryId | LineNumber: 2 | BytePositionInLine: 28."
        ]
    }
}
2 Answers
[RegularExpression("^[1-9]\\d*$", ErrorMessage = "Invalid fieldName.")]
public int countryId { get; set; }

the error message is set above, but actually the json you are sending can not be sent like this, you should set

"countryId": null ,

the json of the request is not correct: you have to pass something as country id:

{
    "currencyCode": "RUB",
    "countryId": "",
    "fields": [{
            "fieldName": "BIC or Bank Code",
            "fieldValue": "12345678901234567"
        },
        {
            "fieldName": "Beneficiary Account Number",
            "fieldValue": "123456"
        }
    ]
}

or

{
    "currencyCode": "RUB",
    "countryId": null,
    "fields": [{
            "fieldName": "BIC or Bank Code",
            "fieldValue": "12345678901234567"
        },
        {
            "fieldName": "Beneficiary Account Number",
            "fieldValue": "123456"
        }
    ]
}
Related