I'm unable to connect to this URL using WebRequestCreator.BrowserHttp, I am however able to connect using WebRequestCreator.ClientHttp. Here's a sample of the code I'm using,
var httpClient = new HttpClient();
WebRequest.RegisterPrefix("http://", WebRequestCreator.BrowserHttp);
var byteArray = Encoding.UTF8.GetBytes("username:password");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
I'm trying to avoid using the 'Windows Security' dialogue box and I cannot use WebRequestCreator.BrowserHttp for my project.
Edit:
When using WebRequestCreator.BrowserHttp I get
System.ArgumentException: Value does not fall within the expected
range
and nothing in fiddler. If I use WebRequestCreator.ClientHttp I get
Authorization: Basic
in Fiddler
I am able to do both Basic and Bearer (JWT) Authentication on a current silverlight project.
/*
* NOTE:
* It turns out that Silverlight provides HTTP handling in both the Browser and Client stack.
* By default Silverlight uses the Browser for HTTP handling.
* The only problem with this is that Browser HTTP Handling only supports GET and POST request methods.
*/
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
var httpClient = new HttpClient();
var byteArray = Encoding.UTF8.GetBytes("username:password");
// Default headers will be sent with every request sent from this HttpClient instance.
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
Related
HttpClient httpClient = new HttpClient();
MyRequest request = new MyRequest (data);
var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(request), System.Text.Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:8000/api/action"),
Content = content,
Method = HttpMethod.Post
};
httpRequestMessage.SetBrowserRequestMode(BrowserRequestMode.NoCors);
await httpClient.SendAsync(httpRequestMessage);
Using HttpClient in Blazor WebAssembly I am trying to send a request to an API.
However, despite specifying application/json as the content type it sends text/plain;charset=UTF-8 (as viewed in the Chrome Network tab). This results in the API throwing an error.
I think you could check these caseļ¼
case1,case2
read this document,and try with PostAsJsonAsync method
I tested as below and worked well:
var weatherforecast = new WeatherForecast() { Date = DateTime.Now, Summary = "testsummary", TemperatureC = 44 };
var response = await Http.PostAsJsonAsync("https://localhost:44385/WeatherForecast", weatherforecast);
Result:
Related post:
Wrong Content-Type being substituted for fetch http request
HttpClient in WebAssembly calls the standard fetch method.
As per the fetch specification when using no-cors only a limited number of content-types can be used:
https://fetch.spec.whatwg.org/#simple-header
"application/x-www-form-urlencoded"
"multipart/form-data"
"text/plain"
The preferred solution would be to correctly configure the end point you are calling to allow cross origin requests and not to use no-cors e.g:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
Access-Control-Allow-Origin: *
If this is not possible (as in my case) and you must use no-cors the only other option would be to change your end point to map "text/plain" to "application/json"
Whilst many may not consider this a bug it is an inconsistency in how HttpClient behaves and is not obvious (though the NoCors option is only available in WebAssembly)
Hello Stackoverflow community. I hope someone here can help me!!
I'm trying to integrate with the Zoopla API that requires the post request to send the following customized content type. (I've got the certificate side of things working fine).
application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json
I've tried the following approaches without any success (they all result in the following error)
System.FormatException: 'The format of value 'application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json' is invalid.'
Initial approach was to set it within the content of the RequestMessage
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list"),
Method = HttpMethod.Post,
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json")
};
When that didn't work I tried to set it via the default headers (the client below is from the ClientFactory)
client.DefaultRequestHeaders.Add("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
My final attempt was to set it without validation
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
I've just tried something else which unfortunately didn't work
string header = "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json";
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(header));
I am well and truly stumped!! HELP!! :-)
Content-Type is set on the content, not in DefaultRequestHeaders. You may try using TryAddWithoutValidation on the request content:
var content = new StringContent("hello");
content.Headers.ContentType = null; // zero out default content type
content.Headers.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
var client = new HttpClient(); // note: use IHttpClientFactory in non-example code
var response = await client.PostAsync("https://postman-echo.com/post", content);
Console.WriteLine(response.StatusCode); // OK
Console.WriteLine(await response.Content.ReadAsStringAsync());
// {"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-6345b568-22cc353761f361483f2c3157","content-length":"5","content-type":"application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json"},"json":null,"url":"https://postman-echo.com/post"}
Running calls to the Design Automation API in Postman works just fine but when I try to make the same calls in C# using HttpClient they fail with a 404 that seems to actually hide an authentication error:
{
"developerMessage":"The requested resource does not exist.",
"userMessage":"",
"errorCode":"ERR-002",
"more info":"http://developer.api.autodesk.com/documentation/v1/errors/err-002"
}
That link leads to an authentication error:
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>1F52E60A45AEF429</RequestId>
<HostId>
[ Some base64 ]
</HostId>
</Error>
I'm following examples for how to use HttpClient, but I may be missing something. I successfully get the access token, run
var client = new HttpClient
{
BaseAddress = new Uri("https://developer.api.autodesk.com/da/us-east")
};
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(TokenType, AccessToken);
then
var result = await client.GetAsync("/v3/forgeapps/me");
and the above json is the result's content. I use the same access token in Postman and it works.
I would wrap up the endpoint, headers, and httpmethod in the HttpRequestMessage. Then send it and assign it to HttpResponseMessage.
var client = new HttpClient
{
BaseAddress = new Uri("https://developer.api.autodesk.com/da/us-east/")
};
//throw the endpoint and HttpMethod here. Could also be HttpMethod.Post/Put/Delete (for your future reference)
var request = new HttpRequestMessage(HttpMethod.Get, "v3/forgeapps/me");
//also maybe try throwing the headers in with the request instead of the client
request.Headers.Add(TokenType, AccessToken);
// send the request, assign to response
HttpResponseMessage response = await client.SendAsync(request);
//then, we can grab the data through the Content
string result = await response.Content.ReadAsStringAsync();
I need to perform an HTTP GET operation while following redirects.
using (var client = new HttpClient())
{
var response = await client.GetAsync("https://example.com");
}
Problem is that if the server returns a 302 HTTP code redirecting to http://... (not https), .NET does not follow it (for security reasons).
How do I force HttpClient to follow redirects from HTTPS to HTTP?
You may have to do a little bit of extra work:
using var client = new HttpClient();
var response = await client.GetAsync("https://example.com");
if (new[] {HttpStatusCode.Moved, HttpStatusCode.MovedPermanently}.Contains(response.StatusCode))
{
response = await client.GetAsync(response.Headers.Location);
}
// more code
I am writing (Attempting to write a crud application!)
I need to send a Key to the server before I can start using the service.
this.InitializeComponent();
client = new HttpClient();
client.BaseAddress = new Uri("http://dignity-network.org/api/");
I have tried
client.BaseAddress = new Uri("NO3ID81WJECJXZI83A3YYPGJKJLNEJMQ#dignity-network.org/api/")
But this does not work, what is the correct request to send authorization to a server ?
Thanks.
All depends how the server accepts and implements authorization code.
if you have to send the auth code before you start to use , you just need:
HttpContent content = HttpContent.Create(yourAuthCode, Encoding.UTF8);
HttpResponseMessage response = client.Post(new Uri ("http://dignity-network.org/api/"), content);