Rest Sharp's AddJsonBody sending parameters in url instead of in body for a POST request - restsharp

I set my application to send a POST request with parameters to be passed in body using
qs.name = name; qs.id = id
request.AddJsonBody(qs)
But on running the application, i can see the individual parameters in my URL as query string parameters

If i Understand correctly you want to send a json a in the body for a post request, You Should use AddParameter(), Instead of AddJsonBody();
Here is a quick example
public IRestResponse ExamplePost(int id, string name)
{
object tmp = new
{
Id = id,
Name = name
};
string json = JsonConvert.SerializeObject(tmp);
var Client = new RestClient();
Client.BaseUrl = new Uri(YourEndPoint); //Your Url
var request = new RestRequest(Method.POST);
request.Resource = string.Format("/someurl");
request.AddParameter("application/json", json, ParameterType.RequestBody);
IRestResponse response = Client.Execute(request);
Logger.LogInfo($"Sending : {json}");
return response;
}
This will send the following json
{"Id":9939,"Name":"Zander"}

Related

OkHttp Post Body as JSON is throwing 404

I recently moved into OKHTTP. I'm able to perform get request but while performing post i'm getting 404. Can someone help me out where I'm going wrong.
FYI:
auth token is correct & url is valid
public void PullRequest() throws IOException{
JSONObject jo = new JSONObject();
jo.put("head","patch-7");
jo.put("base","main");
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jo.toString());
//RequestBody body = RequestBody.create(jo.toString(),JSON);
Request request = new Request.Builder()
.url(url)
.header("Authorization",authorization)
.post(body)
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
if (response.code()>300) {
System.out.println("error...");
System.out.println(response.body().string());
}else {
System.out.println(response.body().string());
}
}

Attaching files to Azure DevOps work item

I am trying to attach files (screenshots) to an Azure DevOps work item via a C# desktop app. I have managed to attach files, but they're not valid image files, which leads me to believe that I'm doing something wrong in uploading them.
From the documentation DevOps Create Attachment below is the section on the Request body of the API call, which is rather vague.
From a GitHub discussion this answer seems to suggest that I just upload the binary content directly, which is what I'm doing.
My code is as follows
var img = File.ReadAllBytes(fname);
string query = #"/_apis/wit/attachments?fileName=" + fname + #"&api-version=6.0"
string response = AzureUtils.AttachFile(query, img, "POST", false, "application/octet-stream");
Is it correct that I literally pass in the byte array which is read from the file (variable img) as the body?
Why is it not a valid file when I look at it in DevOps?
The code for AttachFile is
public static string AttachFile(string query, byte[] data = null, string method = "GET",
bool dontUseBaseURL = false, string contentType = "application/json-patch+json")
{
try
{
HttpWebRequest request = WebRequest.Create(query) as HttpWebRequest;
request.ContentType = contentType;
request.Method = method;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", ["AzurePAT"]))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
request = null;
response = null;
return result;
}

CS1503: Argument 2: cannot convert from ‘System.Net.Http.HttpContent’ to ‘System.Net.Http.HttpCompletionOption’

I'm trying to make a call to another microservice's get method from a service. But when I try to do so, I'm getting this error:
CS1503: Argument 2: cannot convert from ‘System.Net.Http.HttpContent’ to ‘System.Net.Http.HttpCompletionOption’.
Below is the code in the source microservice to get a list of data from the destination service.
this._httpClient.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "relativeAddress");
request.Content = new StringContent(JsonConvert.SerializeObject(invoiceFilterRequest),
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
var response = await this._httpClient.GetAsync(InvEndpoints.GET_Cus_List, request.Content).ConfigureAwait(false);
Actual error is shown in the 2nd parameter request.Content in the GetAsync() call.
Here is the destination service method:
[HttpGet("cus/filter")]
public async Task<ActionResult<PagedList<Inv>>> GetCusByFilterAsync(InvFilterRequest request)
{
try
{
//..
}
}
Is there any simple solution to send object as a parameter using HTTP GET to another microservice other than sending them as a query string using the above code?
Please check the GetAsync(String, HttpCompletionOption) method, when using the GetAsync method, the second parameter should be the HttpCompletionOption, instead of HttpContent.
From your description, it seems that you want to send a request with parameters, if that is the case, you should use the HttpClient.PostAsync method, instead of the HttpClient.GetAsync method, refer the following sample:
var companyForCreation = new CompanyForCreationDto
{
Name = "Eagle IT Ltd.",
Country = "USA",
Address = "Eagle IT Street 289"
};
var company = JsonSerializer.Serialize(companyForCreation);
var requestContent = new StringContent(company, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("companies", requestContent);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var createdCompany = JsonSerializer.Deserialize<CompanyDto>(content, _options);
Reference: Make HTTP requests using IHttpClientFactory in ASP.NET Cor

Getting Swagger API response error StatusCode 404, when called from code

While making an API call from swagger-ui, with content type "application/json", it is working fine. But when the same API is being called from below specified code, shows 404 StatusCode . What could be the possible reasons for it? Also, few other APIs from the same swagger-ui, are when being called from the code, they work from this same code.
var serialized = JsonConvert.SerializeObject(data);
String uri = GetEndpointUrl(path);
String responseData = "";
var buffer = System.Text.Encoding.UTF8.GetBytes(serialized);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.Timeout = TimeSpan.FromSeconds(120);
var response = client.PostAsync(uri, byteContent).Result;
responseData = await response.Content.ReadAsStringAsync();

RESTfull Service is not accepting object as parameter

[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json)]
public string StudentUsers(Student user)
{
return string.Format("Hello {0}", user.Name);
}
Above code is my REST service. And my client code is :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
Student user =
new Stuent {
Name="Test User",
Email = "test#test.com",
Password = "test"
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(user.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, user);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
My service is hosted and I'm using webHttpBinding. When I debug my REST service I'm receiving null in Student object. I am sure that my post method is sending data as I test it by taking Name, Email and Password as parameters at REST service so my data is posted successfully but the thing is my Json data which is posted is not getting converted to Student object. I read somewhere that RESTfull Service will convert that Json data to object. Is that true or we need to convert it explicitly?
You need to sent the Content-Length for your POST-ed data:
request.ContentLength = ms.Length;
see here for more details:
I have fixed the issue by changing WebInvoke to
[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare)]