0

I've been trying to pass string data using [FromBody] but it is always null.

enter image description here

public HttpResponseMessage Post(int id, [FromBody] string value)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Success");
}

enter image description here

1
  • Please post your code as code-formatted text, not screenshot. Would be nice if the request is posted in text form as well Commented Apr 4, 2022 at 2:02

3 Answers 3

2

In ASP.NET Core you cannot simply use Model binding to get the whole JSON body text as string. You have to either create a binding model or read the request body manually:

var bodyText = await this.Request.Content.ReadAsStringAsync();
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry but i'm using ASP.Net
1
[HttpPost]
public HttpResponseMessage Post(int id, [FromBody] string value)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Success");
}

The [HttpPost] attribute tells the routing engine to send any POST requests to that action method to the one method over the other. This is a type of overloading.enter link description here

Comments

0

you can use like below;

        var json = JsonConvert.SerializeObject("your value parameter value");
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        using (var client = new HttpClient())
        {
            try
            {
                client.BaseAddress = new Uri("your url" + "?id=your ID");
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authString);

                HttpResponseMessage Res = client.PostAsync("", content).Result;

                var jsonContent = Res.Content.ReadAsStringAsync().Result;
              
            }
            catch (Exception ex)
            {
                throw;
            }
        }

above codes work in my app.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.