I have read the following:
My particular issue was that the model binding was silently failing for a JSON model. (It was always null).
As I had the exact JSON being posted, I was able to debug it locally by running the web-service locally, and posting to my controller via cURL (can use POSTMAN).
Using the below code, I was able to see the exact exception occurring during serialization.
[HttpPost]
public IActionResult MyAction([FromBody] dynamic request)
{
if (request != null)
{
try
{
var objAttempt =
JsonConvert.DeserializeObject<MyModel>(
JsonConvert.SerializeObject(request));
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
ridiculously, in dot net core you cannot use just "frombody string parameter". you should make a model class for just one string parameter.
public async Task<IActionResult> GetRankings([FromBody] string cookie)
=>
//1. make a model. MyCookie.cs
class MyCookie{
public string Cookie { get; set; }
}
//2. edit your parameter
public async Task<IActionResult> GetRankings([FromBody] MyCookie cookie)
I needed to post string data by .Net Desktop Client to .NET Core host. I was getting unsupported media error. I have followed Shaun Luttin's answer and worked fine. The I found something easier to get just string data as folows in case someone else finds useful:
[HttpPost]
[Route("Request/Echo")]
public async Task<string> Echo()
{
using (var Reader = new StreamReader(Request.Body, Encoding.UTF8))
{
return await Reader.ReadToEndAsync();
}
}
This post is very useful.
I struggled with this for far to long and finally, after looking at what a DevExpress control was doing for "PUT"ting to a Razor Page, I discovered this nugget:
JavaScript
$.ajax({
type: "PUT",
url: "/GoalGrid?handler=Single",
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {values: single }
})
GoalGrid.cshtml.cs
public JsonResult OnPutSingle(string values)
{
// Do stuff with 'values' here
}
The trick is to use the "application/x-www-form-urlencoded; charset=UTF-8" as your contentType for the request. This way you don't need to create a class for a single string value. And things work as expected.
For me, just adding [FromBody]
to the parameters list solved the problem.
May this save someone's time.
You simply need to put the body in quotes such that it represents a string
. You also need to leave the request type as application/json
. That way the media type formatter will figure it out:
"=sec_session_id=[redacted]; _ga=[redacted]; AWSELB=[redacted]"
Should do the trick.