C# .net 4.0 Upload a file to .asp Web API - c#

My .net 4.0 class library send HttpRequestMessage and receive HttpResponseMessage from .asp Web API (REST).
When I sent a small class, I use JSON to parse it as string, then I send string by:
request = new HttpRequestMessage();
request.RequestUri = new Uri(myRestAPI);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = method;
if (method != HttpMethod.Get)
request.Content = new StringContent(content, Encoding.UTF8, mthv);
Next, use HttpClient to send it:
using (HttpResponseMessage httpResponse = _client.SendAsync(request).Result)
{..}
This works fine.
Now, my class has got bigger, How can i send it ?
What i did was to zip it and send as ByteArrayContent.
request = new HttpRequestMessage();
request.RequestUri = new Uri(url);
request.Method = method;
if (method != HttpMethod.Get)
request.Content = new ByteArrayContent(content);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
And send it the same way.
But now the server does reply me with error:
No MediaTypeFormatter is available to read an object of type 'Byte[]' from content with media type 'multipart/form-data'.
What am I doing wrong ?? I am trying to find a proper guide and all the guides are talking about uploading FROM web api and not about uploading from application to web api..

Go get WebAPIContrib, it has a CompressedContent class
With it you can do,
request.Content = new CompressedContent(new StringContent(content, Encoding.UTF8, mthv),"gzip");
and compression will just magically just happen.

Related

C# API Beginner

I have the following code as a start to create a API Call to https://jsonplaceholder.typicode.com/posts/. I want to practice making the call, receive a JSON response and then..do stuff.
How can I finish this off to get a response so I can iterate through the response array.
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,"");
request.Content = new StringContent(URL, Encoding.UTF8,"application/json");
Wiring this in VS Code so will need to install packages if needed.
Thank you!
You are almost there. Try (if you want a simple synchronous send):
HttpClient client = new HttpClient();
string responseString;
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri("<insert your URL>"))) {
HttpResponseMessage response = client.SendAsync(request).Result;
// Get the response content as a string
responseString = response.Content.ReadAsStringAsync().Result;
}
Note that it's good practice to initialize one instance of HttpClient and reuse it to send multiple requests (rather than initialize one every time you need to send something).
Any headers, URLs and such specific to a message should be set in the HttpRequestMessage class (which should be disposed of with the "using ..." term.

Can JSON be sent with HttpClient in C# using the PATCH verb?

I am working with an API that requires a call with the PATCH verb. I am trying to issue a request using the HttpClient object in C#. The request sends, however the JSON is not present in the body. Instead it is blank. Relevant code below.
var patch = new HttpMethod("PATCH");
var http = new HttpRequestMessage(patch, "https://apiendpoint");
var content = new StringContent(json, Encoding.UTF8, "application/json");
http.Content = content;
var result = client.SendAsync(http).Result;
This is my first time using SendAsync, so perhaps I am missing something else that needs to be set on the HttpRequestMessage?

SharePoint 2013 REST API: Updating File Metadata

I am attempting to modify the metadata of a file that has just been uploaded.
using (HttpClient client = new HttpClient(new HttpClientHandler { Credentials = _authenticator.Credential }))
{
client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", _authenticator.Token);
client.BaseAddress = _authenticator.Endpoint;
client.DefaultRequestHeaders.Add("IF-MATCH", "*");
string cmd = String.Format("_api/web/lists/GetByTitle('Drop Off Library')/items({0})", file.Id);
string jsonString = JsonConvert.SerializeObject(file);
StringContent test = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(cmd, test);
}
I successfully GET the file's metadata above, and store it in a SharePoint file model of my own creation. I modify one of the file's metadata fields, and then attempt to merge the deserialized object back in. This has been resulting in a 400 Bad Request error. Any ideas of why this might be happening?
The solution would be to replace the lines:
string jsonString = JsonConvert.SerializeObject(file);
StringContent test = new StringContent(jsonString, Encoding.UTF8, "application/json");
with
var test = new StringContent(JsonConvert.SerializeObject(payload));
test.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
since in your case the invalid Content-Type header is generated.
See JSON Light support in REST SharePoint API released for a list of supported formats.

Adding authentication header to HttpClient

I'm trying to access an API, but all the documentation is in PHP and I'm not very familiar with PHP. I am having trouble authenticating to the API. The documentation is here.
Here is what I have so far
var webAddress = "https://xboxapi.com/v2/latest-xbox360-games";
var httpResponse = (new HttpClient().GetAsync(webAddress)).Result;
httpResponse.EnsureSuccessStatusCode();
var jsonResponse = httpResponse.Content.ReadAsStringAsync().Result;
I'm just not sure how to add the authentication header that they are using in PHP.
Any help would be appreciated.
To add a custom header (in this case X-AUTH), you need to send a custom HttpRequestMessage. For example:
var webAddress = "https://xboxapi.com/v2/latest-xbox360-games";
HttpClient client = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, webAddress);
msg.Headers.Add('X-AUTH', 'your-auth-key-here');
HttpResponseMessage response = await client.SendAsync(msg);

Server is not Recognizing the json, sending request using restSharp

i am trying to post some json to jboss services. using restSharp.. my code is as follows.
RestClient client = new RestClient(baseURL);
RestRequest authenticationrequest = new RestRequest();
authenticationrequest.RequestFormat = DataFormat.Json;
authenticationrequest.Method = Method.POST;
authenticationrequest.AddParameter("text/json", authenticationrequest.JsonSerializer.Serialize(prequestObj), ParameterType.RequestBody);
and also tried this one
RestClient client = new RestClient(baseURL);
RestRequest authenticationrequest = new RestRequest();
authenticationrequest.RequestFormat = DataFormat.Json;
authenticationrequest.Method = Method.POST; authenticationrequest.AddBody(authenticationrequest.JsonSerializer.Serialize(prequestObj));
but in both cases my server is giving me error that json is not in correct format
Try using JsonHelper to prepare your json as the following
string jsonToSend = JsonHelper.ToJson(prequestObj);
and then
authenticationrequest.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
I have found what was going wrong...
i am using RestSharp in windows metro Style, so downloaded source code and make some modifications... so that modifications in the function PutPostInternalAsync i just added this modifications
httpContent = new StringContent(Parameters[0].Value.ToString(), Encoding.UTF8, "application/json");
and it solve the problem....
Parameters[0].Value.ToString() instead of this you can write a method which can return the serialize json object. (as string).

Categories