jsonasp.net-coreasp.net-web-api

Asp.net core: action with raw string parameter


I'm trying to write an action with a raw string parameter.

This string will be parsed dynamically as a json, so the keys in the json are not know at compile time.

I declared the method in this way:

[HttpPost("MyAction")]
public async Task<ActionResult<long>> MyAction([FromBody] string command)
{
    var cmd = MyCqrsCommand(command);
    return await Mediator.Send(cmd);
}

I call the method with swagger that shows a parameter as application/json

enter image description here

The result is this

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|4e0e9c40-4036f8a9873ecac8.",
  "errors": {
    "$": [
      "The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
    ]
  }
}

I found two different solutions:

[HttpPost("MyAction")]
public async Task<ActionResult<long>> MyAction([FromBody] object command)
{ ... }
    
[HttpPost("MyAction")]
public async Task<ActionResult<long>> MyAction(string command)
{ ... }

Using object is not elegant but it works. Using "string" in uri has some limitations, so I prefer the previous.

Which one is the best solution? And is there a way to insert the string in body declared as string and not object?


Solution

  • Which one is the best solution?

    I perfer to use object parameter solution.

    [HttpPost("MyAction")]
    public async Task<ActionResult<long>> MyAction([FromBody] object command)
    { ... }
    

    From the screenshot of your request we can see, you sent a JSON object { "key": "value" } to your MyAction method. So you shouldn't declared your parameter as string.

    And is there a way to insert the string in body declared as string and not object?

    If you expect to use "string" as input parameter, just send the content of value.

        [HttpPost("/MyAction")]
        public async Task<ActionResult<long>> MyAction([FromBody] string command)
    

    enter image description here