If you create an ASP.Net Core API Controller, and you wish to create an endpoint that can accept any string, you would expect this to be correct:
using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Serilog; namespace My.Api.Controllers { [ApiController] [Route("/api/[controller]")] [Produces("application/json")] public class TestController : ControllerBase { [HttpPost()] [ProducesResponseType(200)] [ProducesResponseType(404)] public string PostTest([FromBody] string text) { Log.Information(text); return text; } } }
But this endpoint will only accept strings in quotes, so posting string will not work, and you get the “‘s’ is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.” error. But if you post “string”, the function works.
This is because the method accepts a JSON string, and not a raw string.
There is no direct way of allowing any string to be posted to your endpoint, as the endpoints always expects a type-strong value.
So what can you do?
OPTION 1: CHANGE THE INPUT TO OBJECT
If you know that the input is a JSON object, you can post an object instead:
[HttpPost()] [ProducesResponseType(200)] [ProducesResponseType(404)] public string PostTest([FromBody] object text) { Log.Information(text.ToString()); return text.ToString(); }
This will accept any JSON object (for example { “a”: “b” }), but not a clean string.
OPTION 2: READ FROM THE REQUEST BODY DIRECTLY:
To accept any raw string, you need to indirectly read the request body:
[HttpPost()] [ProducesResponseType(201)] [ProducesResponseType(400)] public async Task<IActionResult> PostTest() { using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { string message = await reader.ReadToEndAsync(); return message; } }
The downside of streaming the request body to a string is that you cannot test the endpoint using Swagger (or OpenApi as it is called today), as there is nowhere to write the request body. To test it you need a tool such as Postman or CURL.
MORE TO READ:
- Accepting Raw Request Body Content in ASP.NET Core API Controllers by Rick Strahl
- Create web APIs with ASP.NET Core from Microsoft
- .NET Core API and CORS – allow POST from Javascript using Microsoft.AspNetCore.Cors by briancaos
Pingback: Handling “415 Unsupported Media Type” in .NET Core API | Brian Pedersen's Sitecore and .NET Blog
Pingback: Serialization and deserialization of ‘System.IntPtr’ instances are not supported. Path: $.TargetSite.MethodHandle.Value | Brian Pedersen's Sitecore and .NET Blog