How do I send a json array to an ASP.NET server? - c#

I wrote this code to send some JSON to a server:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.brilliantit.ir/getDetail.aspx");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//string json = "{\"id\":\"ahbarres\"}";
string json = "{\"id\":\""+label1.Text+"\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
String temp = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
temp = result.ToString();
}
But, I want to send a JSON array to a server. How can I do this?

Related

how to add body in post request c# [duplicate]

This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
i, tried putting body in request but didn't actually worked,
in body i want to put which is in json format {"ClaimNo":"123123"}
i have used this as code:
string ClaimStatus_url = "https:xyz";
WebRequest request = WebRequest.Create(ClaimStatus_url);
request.ContentType = "application/json";
request.Method = "POST";
//request.Headers = "";// i used this for puting body in it but did not work
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string result = reader.ReadToEnd();
using System.Text;
using System.Text.Json;
namespace TestPostData;
public class Data
{
public int ClaimNo { get; set; }
}
public static class Program
{
public static void Main()
{
var postData = new Data
{
ClaimNo = 123123,
};
var client = new System.Net.Http.HttpClient();
var content = new StringContent(JsonSerializer.Serialize(postData), Encoding.UTF8, "application/json");
var response = client.PostAsync("https:xyz", content).Result;
}
}
That is an example of using HttpClient class that is now recommended to use instead WebRequest.
Try this, i hope it will work.
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I would start off by using RestSharp.
dotnet add package RestSharp
Then I would create a DTOS object with the contents that you want to send in the json:
public class DtosObject
{
public string ClaimNo {get; set;}
}
Then pass that in as the object (I would call the class something relevant to the data it contains). If you only are using ClaimNo you could also use a KeyValuePair like this:
var body = new KeyValuePair<string, string>("ClaimNo", "123123");
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
string ClaimStatus_url = "https://qms.xyz.in/FGClaimWsAPI/api/Common/FetchClaimdetails";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(ClaimStatus_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"ClaimNo\":\""+ userProfile.ClaimNumber +"\"}";
//string json = "{\"ClaimNo\":\"CV010831\"}";
//await turnContext.SendActivityAsync(MessageFactory.Text(json, json), cancellationToken);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result1 = "" ;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
result1 = result.Substring(1, result.Length -2); // to bring response result in proper format
}
_claimstaus = GenrateJSON_Claim(result1);
This upper code worked

How to pass data.bind in POST request using C#

i have a web app connected with crm Dynamics 365. I want to create record in an entity using API, but the entity has lookup fields to another entities. I tried this code but it gives bad request error. How can i send the values of the lookup fields in the API?
JSON:{
"msdyn_name": "Asset",
"msdyn_account#odata.bind": "/accounts(7f7e031b-0e20-ea11-a810-000d3a2d54fd)",
"new_externalproj#odata.bind": "/msdynce_externalprojects(ee3f03c6-751f-ea11-a810-000d3a27b751)" }
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
msdyn_name = "Asset",
msdyn_account = "7f7e031b-0e20-ea11-a810-000d3a2d54fd",
new_externalproj = "ee3f03c6-751f-ea11-a810-000d3a27b751"
});
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://XXX.dynamics.com/api/data/v9.1/msdyn_customerassets");
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", String.Format("Bearer {0}", result.AccessToken));
httpWebRequest.Headers.Add("OData-MaxVersion", "4.0");
httpWebRequest.Headers.Add("OData-Version", "4.0");
httpWebRequest.ContentType = "application/json";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}

Passing symbols inside Json through HttpWebRequest

I try to pass message to MS Flow in Json format, using following method, but once I pass any symbols (like ") I get an error as symbols are recognized as code.
public static bool notification(string customer, string comment)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("my msflow link goes here");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"customer\":\"" + customer + "\",\"comment\":\"" + comment + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
return true;
}
catch (Exception)
{
return false;
}
}
Try to use the JSON.NET to serialize your objekt in the code like this:
string json = JsonConvert.SerializeObject(<your object>);

delete a Firebase user using C#

Is it possible to delete a user account in Firebase in C#?
I can successfully create users but on the delete, I get INSUFFICIENT_PERMISSION bu I don't know how to provide the correct permissions.
The code for creating a user:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(NEW_USER_URL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var body = new
{
email = email,
password = password
};
string json = JObject.FromObject(body).ToString();
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
The code for deleting a user:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(DELETE_USER_URL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var body = new
{
localId = uUid
};
string json = JObject.FromObject(body).ToString();
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
The urls:
static string NEW_USER_URL = $#"https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key={ConfigurationManager.AppSettings["FireBaseProjectApiKey"]}";
static string DELETE_USER_URL = $#"https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount?key={ConfigurationManager.AppSettings["FireBaseProjectApiKey"]}";

HttpWebRequest with proxy - setting cookies

Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "someParameters";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
string Bugzilla_logincookie= httpResponse.Headers.ToString();
Bugzilla_logincookie= Bugzilla_logincookie.Substring(plsWork .IndexOf("logincookie") + 12);
Bugzilla_logincookie= Bugzilla_logincookie.Substring(0, plsWork .IndexOf(";"));
CookieContainer cc = new CookieContainer();
cc.SetCookies(new Uri("http://localhost"), Bugzilla_logincookie);
var httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest2.ContentType = "application/json";
httpWebRequest2.Method = "POST";
httpWebRequest2.Proxy.Credentials = new NetworkCredential("username", "password");
httpWebRequest2.CookieContainer = cc;
using (var streamWriter2 = new StreamWriter(httpWebRequest2.GetRequestStream()))
{
string json = "someParametersForJsonCall";
streamWriter2.Write(json);
}
var httpResponse2 = (HttpWebResponse)httpWebRequest2.GetResponse();
using (var streamReader2 = new StreamReader(httpResponse2.GetResponseStream()))
{
var responseText = streamReader2.ReadToEnd();
}
I have problem with using proxy. The thing I'm trying to do is: use a Proxy for http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/User.html to call the login method and then store cookies of response and send them with each call of the session.
I get this error:
"You must log in before using this part of Bugzilla."
What am I mistakenly using?

Categories

Resources