0

I have a client that will send some string data to my web page using JSON, but when I post it, it always returns null for some reason.

Is there anything wrong with my post?

Client:

public async Task TesteAsync(string numeroserie)
{
    try
    {
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(numeroserie);
        var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

        var url = "https://localhost:44336/Home/Receive";
        var client = new HttpClient();

        var response = await client.PostAsync(url, data);

        string result = response.Content.ReadAsStringAsync().Result;
        MessageBox.Show(result);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
        return;
    }
}

Server Side:

[System.Web.Http.HttpPost]
public string Receive(string json)
{
    return json;
}

My server is using ASP.NET MVC.

Server side using breakpoint when the request is made

Client side using break when sending

Update: What i want to do in the end is send to my webserver a string and then return it to the client . I have no experience with json so i don't know if it's correct what i did

JoelFerreira
  • 19
  • 1
  • 7

1 Answers1

0

Look. At first lets check http request.

string url = "YourURL";
string body = JsonConvert.SerializeObject(BodyModel);


HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)
{
   Content = new StringContent(body, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
   string responseString = await response.Content.ReadAsStringAsync();
   ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
}

now lets make some changes in your controller.

[HttpPost]
public JsonResult Receive([FromBody] YourJsonModel parameters)
{
   //Do logic
   return Json(YourResponseModel);
}

Here is the case when you want to pass string and get it as string. In your controller you can use [FromQuery] or just left string both are ok.

[HttpPost]
public string SomeAction(string data) // public string SomeAction([FromQuery] string data)
{
    return data;
}

And here is the request

string url = "http://localhost:15832/YOURCONTROLLERNAME/SomeAction?data=YOURSTRINGVALUE";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)
{
    Content = new StringContent("", Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
    string responseString = await response.Content.ReadAsStringAsync(); // here is your response as string
}

P.S. If you are not sending body, you can change action type to HttpGet. As it comfortable to your task.

Artavazd
  • 132
  • 1
  • 6
  • what if i don't have a model? i just wanna pass a string with some data to the webserver – JoelFerreira Jun 04 '20 at 13:42
  • I'll edit post for your question. Feel free for any question :) – Artavazd Jun 04 '20 at 13:59
  • in your string url u have "http://localhost:15832/YOURCONTROLLERNAME/SomeAction?data=YOURSTRINGVALUE"; my value is passed in the method before like: public async Task TesteAsync(string numeroserie) i need to send that string into the server – JoelFerreira Jun 04 '20 at 14:27
  • I tried but i keep receiving null.. it's reaching there .. is it maybe the way im calling it? code: HttpRequest httpRequest = new HttpRequest(); _ = httpRequest.TesteAsync(numeroserie); – JoelFerreira Jun 04 '20 at 14:33
  • have you tried the same way as I've mentioned? I have tested it befor to put it here. – Artavazd Jun 04 '20 at 15:44
  • By adding "?=" to your url end will resolve it.And if you have other parameters in query you can and "&" to declare the rest. – Artavazd Jun 04 '20 at 15:56
  • So will it be like this: public async Task TesteAsync(string numeroserie) { string url = "https://localhost:44336/Home/Receive?data==" ; ?? numeroserie is a string wich contains the numbers i want to send.. it's a variable.. i can bind that variable into the link ? – JoelFerreira Jun 04 '20 at 16:10
  • Look, just let your original url, and add there this: `url + "?data=" + numeroserie` – Artavazd Jun 04 '20 at 16:16
  • Ok it worked but , the url is sending data like this: "https://localhost:44336/Home/Receive?data=189-985-598" but my method isn't receiving the data value – JoelFerreira Jun 04 '20 at 16:27
  • Um, sorry I forgot that your method parameter name is json insted of data. Just rename data to json and that will work. – Artavazd Jun 04 '20 at 16:51
  • In the future if you will use other paramteres, you have to add its names with values, that action could understand and recognize them. Like , string fruits, string water >>> ?fruits=apples&water=full – Artavazd Jun 04 '20 at 16:54