Ask Your Question
4

How can the response from a POST request be changed from HTML to JSON in C#?

asked 2023-06-26 03:03:45 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-26 03:12:02 +0000

pufferfish gravatar image

To change the response from a POST request from HTML to JSON in C#, you can add a header to the request indicating that you want the response to be in JSON format.

Here is an example code snippet that uses the HttpClient class in C# to make a POST request and get a JSON response:

```# using System; using System.Net.Http; using System.Threading.Tasks;

public static async Task<string> PostRequest(string url, string data) { using (var httpClient = new HttpClient()) { var content = new StringContent(data); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var response = await httpClient.PostAsync(url, content);

    if (response.IsSuccessStatusCode)
    {
        var jsonResponse = await response.Content.ReadAsStringAsync();
        return jsonResponse;
    }
    else
    {
        // handle error response
        return "";
    }
}

} ```

In this code, we create a StringContent object with the data we want to post and set the content type header to "application/json". This tells the server that we want to receive a JSON response.

Then we make the POST request using the HttpClient.PostAsync method and read the response content as a string. If the response is successful, we return the JSON response string. Otherwise, we handle the error response as needed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-26 03:03:45 +0000

Seen: 8 times

Last updated: Jun 26 '23