Quite a simple problem I've got that would be easy to solve I reckon for the brains. It's just a tried a different queries on Google and nothing popped up but hey that's why I am here.
Here is the error:
System.InvalidOperationException
Basically this error is thrown on this piece of code here
string test = response.Content.Headers.GetValues("Location").FirstOrDefault();
Location in Fiddler looks like this:
Location: https://www.redirecturlishere.com/blah
Here is the entire function:
private async Task<string> GetRequest()
{
//HttpContent postContent = new StringContent(post, Encoding.ASCII, "application/x-www-form-urlencoded");
using (HttpResponseMessage response = await httpClient.GetAsync(
"http://www.cant-share-url.com"))
{
using (HttpContent content = response.Content)
{
string test = response.Content.Headers.GetValues("Location").FirstOrDefault();
}
}
return "";
}
More details on the error, "Additional information: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."
I don't think there is much else to explain so I'll leave it at that.
I have solved the problem basically the header was not stored in the content, silly me.
And for anyone who doesn't see the solution. :)
string test = response.Headers.GetValues("Location").FirstOrDefault()
Related
Hey guys,
I have a problem with my code. Since about a week my code is not working anymore without any changes. I am pretty sure, that my could should work. All I get is Error 404: forbidden.
Below is a snippet of my Code. I also read about adding a header of the webclient, which did not help. Any other suggestions? I am sorry if my syntax is not that good, it is my first post on stackoverflow.
Thanks in advance!
string epicId = "ManuelNotManni";
WebClient webClient = new WebClient();
Uri uri = new Uri("https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/");
string result = String.Empty;
try
{
string website = $"{uri.ToString()}{epicId}?";
result = webClient.DownloadString(website);
}
catch (Exception ex)
{
Console.WriteLine($"Error:\n{ex}");
Console.ReadLine();
}
finally
{
webClient.Dispose();
}
This is the exact error:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.Net.WebClient.GetWebResponse(WebRequest request)
at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream)
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at TestProject.Program.Main(String[] args) in > C:\Users\Manue\source\repos\TestProject\Program.cs:line 17
You're right. Your code should work fine.
Issue is that URL you're requesting which is actually:
https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/ManuelNotManni?
This returns a 403 status code in any case - no matter if you use a browser, your code or for example postman.
I suggest to have a look at the response body while using postman.
It shows this
<html class="no-js" lang="en-US">
<!--<![endif]-->
<head>
<title>Attention Required! | Cloudflare</title>
<meta name="captcha-bypass" id="captcha-bypass" />
Tracker.gg wants API users to register their apps with them before they're given access to the API.
What you need to do is to first head to their Getting Started page. Here you will have to create an app, which should give you an authentication key.
When you have done this, you want to change your code slightly to add the Authentication Header. Like so for example:
var webClient = new WebClient();
webclient.Headers.Add("TRN-Api-Key", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
As a sidenote, WebClient has been deprecated and it's recommended to use HttpClient from now on. Here's your code with HttpClient instead:
var epicId = "ManuelNotManni";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("TRN-Api-Key", "YOUR API KEY GOES HERE");
// Simplifying Uri creation:
var uri = new Uri($"https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/{epicId}");
var result = string.Empty; // C# prefers lowercase string
try
{
var response = await httpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
else
{
Console.WriteLine($"Unable to retrieve data for {epicId}.");
Console.WriteLine($"Statuscode: {response.StatusCode}");
Console.WriteLine($"Reason: {response.ReasonPhrase}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error:\n{ex}");
Console.ReadLine();
}
finally
{
httpClient.Dispose();
}
This happens when we violate the Firewall rule set by Cloudflare, you can visit this blog for more details.
https://community.cloudflare.com/t/community-tip-fixing-error-1020-access-denied/66439
I'm making a really simple call to an API to receive some data. I need to send headers to get authorized also I need to send some content on the body. This is what I came up with :
public async Task<List<LoremIpsum>> LoremIpsumJson()
{
LoremIpsum1 data = null;
try
{
var client = new HttpClient();
//now lets add headers . 1.method, 2.token
client.DefaultRequestHeaders.Add("Method", "LoremIpsumExample");
client.DefaultRequestHeaders.Add("Token", "sometoken");
HttpContent content = new StringContent("{\"Name\":\"John\",\"Surname\":\"Doe\",\"Example\":\"SomeNumber\"}", Encoding.UTF8, "application/json");
// ==edit==
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync("www.theUrlToTheApi", content);
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<QueueInfo>(json);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
}
return data.data;
Debug.WriteLine(data.data);
}
The app breaks after response.EnsureSuccessStatusCode(); because the request obviously is not successful.
I think I'm really missing something really simple here. How can I do this call?
The error is
StatusCode: 406, ReasonPhrase: 'Not Acceptable'
There could be many reasons for this not working. For instance: keyvalues.ToString() is most likely not putting in the value you want. Seems like you might need to serialize to json rather than just calling .ToString().
Use a tool like postman first and get it working there so you have a working example then try and recreate in C#. It will make your life a lot easier.
For everyone coming here to find a solution.
HttpContent cannot take a header much o less a content-type. There was a typo on adding the content-type which was supposed to be added in HttpClient in this way:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
I am having trouble reading the Location header from parts of a multipart response of an http request. I am using HttpClient, and processing the resultant HttpResponseMessage (mostly) as follows:
protected internal virtual async Task ProcessMultiPartResponseAsync(HttpResponseMessage response)
{
var multipart = await response.Content.ReadAsMultipartAsync();
await Task.WhenAll(multipart.Contents.Select(ProccessContentAsync));
}
protected async Task ProccessContentAsync(HttpContent content)
{
var location = content.Headers.GetValues("Location").FirstOrDefault(); //nada
//...
}
I have verified the Location header is actually in the response using fiddler:
And that the other headers are being read successfully:
From inspecting the non-public property headers.invalidHeaders I see Location listed, as shown below, which seems suspect to me...
Is that my problem? If so how can I get around it. If not what am I doing wrong? Thank you so much for any help.
I have an app on Windows Phone Store, it's a Feedly client and some of my users have been reporting an error for a while.
The error is a JsonReaderException: Unterminated string. Expected delimiter: ". Path 'items[0].summary.content', line 1, position 702
Looking at the error, it seems that the HttpClient didn't download the entire Json, since the position is the end of the response and the response seems incomplete.
Here is one of the responses:
{
"id":"user/{userIdOmmited}/category/global.all",
"updated":1417324466038,
"continuation":"149ebfc5c13:c446de6:113fbbc6",
"items": [{
"id":"HBKNOlrSqigutJYKcZCnF5drtVL1uLeqMvamlHXyreE=_149ff1f0f76:213a17:34628bd3",
"fingerprint":"eb0dc432",
"originId":"https://medium.com/p/7948bfedb1bc",
"updated":1417324463000,
"title":"Iran’s Stealth Drone Claims Are Total BS",
"published":1417324463000,"crawled":1417324466038,
"alternate":[{
"href":"https://medium.com/war-is-boring/irans-stealth-drone-claims-are-total-bs-7948bfedb1bc",
"type":"text/html"
}],
"summary":{
"content":"<div><p><a href=\"https://medium.com/war-is-boring/irans-stealth-drone-claims-are-total-bs-7948bfedb1bc\"><img height=\"200
This is the entire Json of one of the responses, as you can see it ends suddenly at the summary.content, that's why Json.Net can't deserialize it.
My Get method looks like this:
protected async Task<T> GetRequest<T>(string url)
{
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;
using (var client = new HttpClient(handler))
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
if (authentication != null)
request.Headers.Authorization = authentication;
var result = await client.SendAsync(request);
result.EnsureSuccessStatusCode();
var data = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(data.EscapeJson());
}
}
I pass the response DTO as a generics parameter to the method and it deserializes the Json.
The EscapeJson method in the return looks like this:
public static string EscapeJson(this string stringToEscape)
{
return Regex.Replace(stringToEscape, #"(?<!\\)\\(?!"")(?!n)(?!\\)", #"\\", RegexOptions.IgnorePatternWhitespace);
}
I've added this to try to solve the problem because I thought the problem was with the back slashes, but it wasn't (before I found out the json wasn't being downloaded completely).
I've been searching for a solution for this problem for a few weeks, and I couldn't come up with an answer.
In my research I found out that there is a parameter in the SendAsync that is the completionOption, which is an enum, HttpCompletionOption, that has two options: ResponseContentRead and ResponseHeadersRead.
The problem is that I don't know which one is the default and I don't know if changing this will solve the problem since I can't reproduce the problem myself, so I can't test it.
Does anyone has an idea of what might be the problem here?
Could it be a Timeout of sorts or this HttpCompletionOption?
I've been seeing the error for a while, searching for an answer and I have no clue on what might be going on.
Thanks in advance for the help!
Make one HttpClient for the app to use. Do not dispose it. HttpClient is supposed to be reused and not disposed pr request. That is most likely the error.
Let me start by showing code:
private async Task<bool> session()
{
string post = " ";
HttpContent postContent = new StringContent(
post,
Encoding.ASCII,
"application/x-www-form-urlencoded");
using (HttpResponseMessage response = await this.httpClient.PostAsync(
"CANT_SHARE_URL.com/data", postContent))
using (HttpContent content = response.Content)
{
this.session =content.Headers.GetValues("session").FirstOrDefault();
}
return true;
}
I can't disclose the url.
The problem is that it does not set the session variable and the content has returned the headers the header is also showing up in fiddler. The exception 'System.InvalidOperationException' I've tried most obvious options it's certainly responding correctly and I somehow got the headers into a string but I can't remember how.
Are you sure the session header is on the Content? Have you tried looking in the request.Headers collection?