SteinTech
SteinTech

Reputation: 4068

getting json error when invoking asp.net core action

I got this simple request to an action in an asp.net core controller.

Controller:

[ApiController]
public class SystemAPIController : ControllerBase
{
    [HttpPost("systemAPI/SetCulture")]
    public async Task SetCulture([FromBody] string culture)
    {
        this.HttpContext.Session.SetString("Culture", culture);
    }
}

The JSON in the body:

{
    "culture": "nb-NO"
}

I get the following error when invoking the action using postman:

        "The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."

Upvotes: 1

Views: 115

Answers (1)

Guru Stron
Guru Stron

Reputation: 141755

You need to create a class which will represent the json structure:

public class Request
{
    public string culture {get;set;}
}

And use it as incoming action parameter:

[HttpPost("systemAPI/SetCulture")]
public async Task SetCulture([FromBody] Request request)
{
    this.HttpContext.Session.SetString("Culture", request.culture);
}

Also common naming convention for properties in C# is PascalCasing but to support it you will either set up it globally or use JsonPropertyNameAttribute per property:

public class Request
{
    [JsonPropertyName("culture")]
    public string Culture {get;set;}
}

Upvotes: 2

Related Questions