How to add access-control-allow-methods to method in C# POST - c#

I am trying to sending a POST to a java web-service with my windows phone app using this c# code:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
var requestContent = new StringContent(json);
requestContent.Headers.ContentType = new
MediaTypeWithQualityHeaderValue("application/json");
var response = await client.PostAsync(requestUri, requestContent);
//...
}
but I am getting a 400 Bad Request and sending this header:
POST [myreq] HTTP/1.1
Content-Type: application/json
Content-Length: 340
Accept-Encoding: identity
Accept: application/json
User-Agent: NativeHost
Host: [myhost]
Connection: Keep-Alive
Pragma: no-cache
and the only difference that I see from a valid similar (to the same web service) android java request is this line in my header:
access-control-allow-methods=[POST]
How to include this access-control-allow-methods with C#?

for future help
client.DefaultRequestHeaders.Add("Access-Control-Allow-Methods", "POST");

Related

Restsharp adds guid to body, how do I remove it?

My code is below, it is very simple. I was trying to match a postman call and it came pretty close, but when I made the call in postman it looks different, specifically restsharp adds a guid around the body that I saw in fiddler. The guide seems to break my calls, how do I remove it?
string url = "https://url/api/";
var client = new RestClient(url);
client.AddDefaultHeader("x-ads-dev", "Key");
var request = new RestRequest("telemetry", Method.Post);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", datapoint, ParameterType.RequestBody);
var response = await client.PostAsync(request);
And here is what Fiddler shows:
POST http://url/api/telemetry HTTP/1.1
Host: api.adsprism.com
x-ads-dev: key
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: RestSharp/107.3.0.0
Accept-Encoding: gzip, deflate, br
Content-Type: application/json; boundary="717cb9fd-684d-424e-bd0a-cf6b0bb11bac"
Content-Length: 398
--717cb9fd-684d-424e-bd0a-cf6b0bb11bac
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="application/json"
[{"entityID":2123,"locationID":33,"data":[{"dateTime":"2020-08-03 23:05:00","reading":0,"flags":0,"quality":15,"ignore":false},{"dateTime":"2020-09-27 03:10:00","reading":0,"flags":0,"quality":15,"ignore":false}]}]
--717cb9fd-684d-424e-bd0a-cf6b0bb11bac--
The --717cb9fd-684d-424e-bd0a-cf6b0bb11bac-- guid is not there in the fiddler postman request and it seems to be causing a bad request error from restsharp. So how do I make restsharp not generate it?
EDIT: Added postman fiddler to show the difference.
POST http://api.url/api/telemetry HTTP/1.1
x-ads-dev: key
Content-Type: application/json
User-Agent: PostmanRuntime/7.29.0
Accept: */*
Postman-Token: 5f186e6d-cad0-482c-b7b8-a50559f24b87
Host: api.adsprism.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 513
[
{
"entityID": 2123,
"locationID": 33,
"data": [
{
"dateTime": "2020-08-03 23:05:00",
"reading": 0,
"flags": 0,
"quality": 0,
"ignore": true
},
{
"dateTime": "2020-09-27 03:10:00",
"reading": 0,
"flags": 0,
"quality": 0,
"ignore": true
}
]
}
]
Reading the docs can help.
const string url = "https://url/api/";
var client = new RestClient(url);
client.AddDefaultHeader("x-ads-dev", "Key");
var request = new RestRequest("telemetry", Method.Post);
request.AddStringBody(datapoint, DataType.Json);
var response = await client.PostAsync(request);

use HttpClient to set the Content-Type to "application/json" and add object to the body

I'm trying to create the following post using HttpClient, using postman its working correctly but I cant seem to replicate it in code. I need to set the header Content-Type to application/json and have an object in the body of the post.
POST https://mycompanyurl.com/authenticate
HEADERS
Key: Content-Type, Value: application/json
BODY
{
"username": "someusername",
"password": "somepassword"
}
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://companyurl.com");
var serializedObject = JsonConvert.SerializeObject(
new {username = "username", password = "password" });
var request = new HttpRequestMessage(HttpMethod.Post, "authenticate");
request.Content = new StringContent(serializedObject, Encoding.UTF8,"application/json");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
}
Using the reverse proxy in fidder I can capture the raw call from postman which works, the rest api returns a result as expected:
POST http://127.0.0.1:8888/v1/authenticate HTTP/1.1 Content-Type: application/json;charset=UTF-8 cache-control: no-cache Postman-Token: 4db8f2dd-cbf0-413c-ad5b-20af0543a31d User-Agent: PostmanRuntime/7.6.0 Accept: / Host: 127.0.0.1:8888 accept-encoding: gzip, deflate content-length: 87 Connection: keep-alive
{"username":"username","password":"password"}
My call from HttpClient and using fiddler is below, This does not work, returns 200 but its not working correctly, data is not being returned, I cant see anything differences in the payload that will make the rest api not respond as expected.
POST http://127.0.0.1:8888/v1/authenticate HTTP/1.1 Content-Type: application/json; charset=utf-8 Host: 127.0.0.1:8888 Content-Length: 87 Expect: 100-continue Connection: Keep-Alive
{"username":"username","password":"password"}
The logic below should generate the same working request signature provided in your example (which was posted as an Answer, please edit your Question instead), and therefore should work:
var clientHandler = new HttpClientHandler
{
AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate,
AllowAutoRedirect = false
};
using (var client = new HttpClient(clientHandler, true))
{
client.BaseAddress = new Uri("http://127.0.0.1:8888/v1/");
client.DefaultRequestHeaders.Add("cache-control", "no-cache");
client.DefaultRequestHeaders.Add("Postman-Token", "db8f2dd-cbf0-413c-ad5b-20af0543a31d");
client.DefaultRequestHeaders.Add("User-Agent", "PostmanRuntime/7.6.0");
client.DefaultRequestHeaders.Add("Accept", "*/*");
client.DefaultRequestHeaders.ExpectContinue = false;
var serializedObject = JsonConvert.SerializeObject(
new { username = "username", password = "password" }
);
var request = new HttpRequestMessage(HttpMethod.Post, "authenticate")
{
Content = new StringContent(serializedObject, Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
}
It will create the following request:
POST http://127.0.0.1:8888/v1/authenticate HTTP/1.1
cache-control: no-cache
Postman-Token: db8f2dd-cbf0-413c-ad5b-20af0543a31d
User-Agent: PostmanRuntime/7.6.0
Accept: */*
Content-Type: application/json; charset=utf-8
Host: 127.0.0.1:8888
Content-Length: 45
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{"username":"username","password":"password"}
Hope this helps.

Authentication error using token with c# httpclient

I have a HttpClient that I am using to use a REST API. However I am having trouble setting up the Authorization header. I need to set the header to the token I received from signin method, but when I use it in another method I get an authentication error.
var invoiceObj = new InvoiceUploadObj { dataFile = file, credential = "", domain = "" };
var invoiceObjSerialized = JsonConvert.SerializeObject(invoiceObj);
var data = new StringContent(invoiceObjSerialized, Encoding.UTF8, "application/json");
HttpClient clientDemoWS = new HttpClient();
clientDemoWS.BaseAddress = new Uri("https://www.nameservice.com");
clientDemoWS.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
clientDemoWS.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", String.Format("Bearer {0}", bearer_token));
HttpResponseMessage responseUpload = clientDemoWS.PostAsync("/services/invoice/upload", data).Result;
The status code is 200, but when I deserialize the server response I get an authentication error as error description.
Checking with Fiddler I see that this is the header:
POST /services/invoice/upload HTTP/1.1
Accept: application/json
Authorization: Bearer eyJ0eXAi......
Content-Type: application/json; charset=utf-8
Host: www.nameservice.com
Content-Length: 4623
Expect: 100-continue
Where am I wrong?

how to post data to url using c#

i want send this data using post method in c#
POST https://lyncweb.contoso.com/ucwa/oauth/v1/applications/103...740/onlineMeetings/ myOnlineMeetings HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Bearer cwt=AAEB...buHc
X-Ms-Origin: http://localhost
X-Requested-With: XMLHttpRequest
Referer: https://lyncweb.contoso.com/Autodiscover/XFrame/XFrame.html
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; Trident/6.0;.NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; InfoPath.3)
Host: lyncweb.contoso.com
Content-Length: 185
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
{
"attendanceAnnouncementsStatus":"Disabled",
"description":"hey guys let's do a musical!",
"subject":"holiday party",
"attendees": ["sip:Chris#contoso.com","sip:Alex#contoso.com"],
"leaders": []
}
please help me to write code in c# desktop application.
You can use Restsharp it is an lib that you can get from Nuget. very easy to use:
here is an example:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();

Http Authorization Header

I would like to get the response of a json api provided by some website this is their cURL Request
curl --include --header "X-Access-Token: XXXXX" "http://api.travelpayouts.com/v2/prices/latest?"
trying to get the content using
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-Access-Token", "XXXXX");
HttpResponseMessage response = await client.GetAsync(url);
var contents = await response.Content.ReadAsStringAsync();
MessageBox.Show(contents);
}
but still getting
{"success":false,"data":null,"message":"Unauthorized"}
Are you sure that you are using token? in your code it looks like a marker.
Here is my output:
#e:~$ curl --include --header "X-Access-Token: d273e9325fXXXXXXXXXXXXX" "http://api.travelpayouts.com/v2/prices/latest?currency=rub&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0"
HTTP/1.1 200 OK
Server: nginx/1.2.4
Date: Wed, 25 Nov 2015 13:53:52 GMT
Content-Type: application/json;charset=utf-8
Content-Length: 7083
Connection: keep-alive
Vary: Accept-Encoding
Status: 200 OK
X-Content-Type-Options: nosniff
{"success": true, "data":

Categories