[c#] How to send json data in POST request using C#

I want to send json data in POST request using C#.

I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file.

How can i send request using these two data forms.

Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"}

For other APIs request body should retrieved from external json file.

This question is related to c# json asp.net-mvc web-services rest

The answer is


You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Questions with c# tag:

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with json tag:

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.? JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to format JSON in notepad++ No String-argument constructor/factory method to deserialize from String value ('') Returning JSON object as response in Spring Boot TypeError: Object of type 'bytes' is not JSON serializable How to send json data in POST request using C# Passing headers with axios POST request How to convert JSON string into List of Java object? npm notice created a lockfile as package-lock.json. You should commit this file RestClientException: Could not extract response. no suitable HttpMessageConverter found Load json from local file with http.get() in angular 2 Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays' How to loop through a JSON object with typescript (Angular2) How to push JSON object in to array using javascript How to check if a key exists in Json Object and get its value REST API - Use the "Accept: application/json" HTTP Header react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined ASP.NET Core return JSON with status code python JSON object must be str, bytes or bytearray, not 'dict Writing JSON object to a JSON file with fs.writeFileSync Convert a JSON Object to Buffer and Buffer to JSON Object back How to parse JSON in Kotlin? How to convert FormData (HTML5 object) to JSON console.log(result) returns [object Object]. How do I get result.name? tsconfig.json: Build:No inputs were found in config file Python - How to convert JSON File to Dataframe How to define Typescript Map of key value pair. where key is a number and value is an array of objects Retrofit 2: Get JSON from Response body Refused to execute script, strict MIME type checking is enabled? Decode JSON with unknown structure How to parse a JSON object to a TypeScript Object Deserialize Java 8 LocalDateTime with JacksonMapper Getting an object array from an Angular service Python - Convert a bytes array into JSON format Passing bash variable to jq Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ What is the difference between json.load() and json.loads() functions Import JSON file in React using setTimeout on promise chain Make XmlHttpRequest POST using JSON

Questions with asp.net-mvc tag:

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core localhost refused to connect Error in visual studio ASP.NET 5 MVC: unable to connect to web server 'IIS Express' How to use SqlClient in ASP.NET Core? Pass Model To Controller using Jquery/Ajax How can I make my string property nullable? Could not find a part of the path ... bin\roslyn\csc.exe CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default How to remove error about glyphicons-halflings-regular.woff2 not found Adding ASP.NET MVC5 Identity Authentication to an existing project ASP.NET Web API : Correct way to return a 401/unauthorised response Effectively use async/await with ASP.NET Web API The page cannot be displayed because an internal server error has occurred on server Calling Web API from MVC controller Rendering partial view on button click in ASP.NET MVC Bootstrap fixed header and footer with scrolling body-content area in fluid-container Display List in a View MVC Phone Number Validation MVC How to get 'System.Web.Http, Version=5.2.3.0? How to call controller from the button click in asp.net MVC 4 How to extend available properties of User.Identity How to pass multiple parameters from ajax to mvc controller? @Html.DisplayFor - DateFormat ("mm/dd/yyyy") How to get DropDownList SelectedValue in Controller in MVC MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource How to add/update child entities when updating a parent entity in EF Return HTML from ASP.NET Web API Jquery Ajax, return success/error from mvc.net controller There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country System.web.mvc missing How to get JSON object from Razor Model object in javascript error CS0103: The name ' ' does not exist in the current context How to return a file (FileContentResult) in ASP.NET WebAPI Return JsonResult from web api without its properties Using a PagedList with a ViewModel ASP.Net MVC How to call MVC Action using Jquery AJAX and then submit form in MVC? onchange event for html.dropdownlist How to update a claim in ASP.NET Identity? Make sure that the controller has a parameterless public constructor error @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array

Questions with web-services tag:

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice How can I get the named parameters from a URL using Flask? Connect HTML page with SQL server using javascript PUT and POST getting 405 Method Not Allowed Error for Restful Web Services Create a asmx web service in C# using visual studio 2013 PowerShell script to check the status of a URL Java String to JSON conversion java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of WCF Exception: Could not find a base address that matches scheme http for the endpoint SOAP vs REST (differences) 415 Unsupported Media Type - POST json to OData service in lightswitch 2012 What is the difference between a web API and a web service? SOAP request to WebService with java IntelliJ, can't start simple web application: Unable to ping server at localhost:1099 how to fix java.lang.IndexOutOfBoundsException How to POST URL in data of a curl request Read response body in JAX-RS client from a post request Angular JS POST request not sending JSON data jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF How to get info on sent PHP curl request What is the difference between JAX-RS and JAX-WS? Junit test case for database insert method with DAO and web service How can I pass a username/password in the header to a SOAP WCF Service Working Soap client example How to do a SOAP Web Service call from Java class? HTTP POST and GET using cURL in Linux Uri not Absolute exception getting while calling Restful Webservice Difference between a SOAP message and a WSDL? Jquery Ajax Call, doesn't call Success or Error Default username password for Tomcat Application Manager how to increase MaxReceivedMessageSize when calling a WCF from C# How correctly produce JSON by RESTful web service? UEFA/FIFA scores API How to consume REST in Java How to generate service reference with only physical wsdl file what's the correct way to send a file from REST web service to client? Importing xsd into wsdl How to create web service (server & Client) in Visual Studio 2012? how to send an array in url request

Questions with rest tag:

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request Sending the bearer token with axios What is the recommended project structure for spring boot rest projects? http post - how to send Authorization header? Send POST data via raw json with postman How to download excel (.xls) file from API in postman? Body of Http.DELETE request in Angular2 How to POST form data with Spring RestTemplate? Spring Resttemplate exception handling Pass multiple parameters to rest API - Spring org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? Making a PowerShell POST request if a body param starts with '@' download a file from Spring boot rest service Spring Boot REST API - request timeout? How to pass List<String> in post method using Spring MVC? Http Post request with content type application/x-www-form-urlencoded not working in Spring How to send a POST request using volley with string body? REST API - file (ie images) processing - best practices No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy How to set base url for rest in spring boot? Add my custom http header to Spring RestTemplate request / extend RestTemplate CORS with spring-boot and angularjs not working How do I retrieve query parameters in Spring Boot? Spring Boot: Cannot access REST Controller on localhost (404) How to solve maven 2.6 resource plugin dependency? When do I use path params vs. query params in a RESTful API? Spring MVC - How to return simple String as JSON in Rest Controller What is the difference between resource and endpoint? How to download a file using a Java REST service and a data stream For Restful API, can GET method use json data? can you add HTTPS functionality to a python flask web server? How to send post request to the below post method using postman rest client How do I call REST API from an android app? Trying to use Spring Boot REST to Read JSON String from POST InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately Convert a object into JSON in REST service by Spring MVC Date format in the json output using spring boot Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3 How to export specific request to file using postman? Spring Boot REST service exception handling