I am working on consuming Json data in Windows RT. I followed steps from this link as follows
protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
{
if(request.Method==HttpMethod.Get)
{
request.Headers.Add("abcustom", "reqvalue");
}
return request;
}
But, at ProcessRequest I have an error which says:
no suitable method found to override
I should use System.Web.HttpContext but I can't use it, because of Windows RT. How can I fix it?
Try use this:
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://www.domain.com");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/YourPath");
request.Content = new StringContent(jsonStringToSend, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
string json = await response.Content.ReadAsStringAsync();
now you have a variable called json witch contains the response from the server, and you can process it now.
Related
Good day,
I am currently using ASP.NET Core to make request to some service endpoints with strict Header rules.
I discovered that RequestId is added automatically to my request header, i need to remove this.
Here is my code snippet;
client.BaseAddress = new Uri(mainUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authorization);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
var responseMessage = await client.PostAsJsonAsync(mainUrl, model);
var errorMessage = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
StreamReader sr = new StreamReader(await responseMessage.Content.ReadAsStreamAsync());
resps = sr.ReadToEnd();
I also tried using flur but the situation remains thesame. Below is the snippet of the code;
var resps = await url.AppendPathSegment("/merchant/api/paymentinit")
.WithHeader("Authorization", authorization)
.PostJsonAsync(model)
.ReceiveString();
I have also tried following suggestion from enter link description here
But nothing seems to work. Can someone put me in the right direction?
You'll need to create a DelegatingHandler and set Activity.Current = null
public class DisableActivityHandler : DelegatingHandler
{
public DisableActivityHandler(HttpMessageHandler innerHandler) : base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Activity.Current = null;
return await base.SendAsync(request, cancellationToken);
}
}
To read more about this issue see David Fowlers comments here
https://github.com/dotnet/aspnetcore/issues/19044
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.
When I try to do the code below, it just results in Invalid Content Type (with error number 612).
I'm trying to delete a lead id from a static list. I can add lead ids or get the static list leads fine.
The post and get calls I make are working fine, although the post calls I make seem to require the data right on the url string (as in $"{endpointURL}/rest/v1/lists/{listID}/leads.json?id={leadID}"; If I include the id as a json object, it fails too. This might be a clue to what I'm doing wrong with the delete call.
string url = $"{endpointURL}/rest/v1/lists/{listID}/leads.json?id={leadID}";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", _access_token);
HttpResponseMessage response = await client.DeleteAsync(url);
The response here always results in Invalid Content Type.
If I add this line before I do the deleteasync call, it gives me a different error before it even hits the deleteAsync call.
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
Error is "Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."
Try using HttpRequestMessage in your code like this
string url = $"{endpointURL}/rest/";
HttpClient client = new HttpClient
{
BaseAddress = new Uri(url)
};
//I'm assuming you have leadID as an int parameter in the method signature
Dictionary<string, int> jsonValues = new Dictionary<string, int>();
jsonValues.Add("id", leadID);
//create an instance of an HttpRequestMessage() and pass in the api end route and HttpMethod
//along with the headers
HttpRequestMessage request = new HttpRequestMessage
(HttpMethod.Delete, $"v1/lists/{listID}") //<--I had to remove the leads.json part of the route... instead I'm going to take a leap of faith and hit this end point with the HttpMethod Delete and pass in a Id key value pair and encode it as application/json
{
Content = new StringContent(new JavaScriptSerializer().Serialize(jsonValues), Encoding.UTF8, "application/json")
};
request.Headers.Add("Bearer", _access_token);
//since we've already told the request what type of httpmethod we're using
//(in this case: HttpDelete)
//we could just use SendAsync and pass in the request as the argument
HttpResponseMessage response = await client.SendAsync(request);
The solution turned out to be a combination of a couple of suggestions.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, data);
// The key part was the line below
request.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
if (!string.IsNullOrEmpty(_access_token))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _access_token);
}
HttpResponseMessage response = await client.SendAsync(request);
This worked for me.
I'm working in a code developed by someone else and I found this lines
HttpResponseMessage response = await Client.PostAsJsonAsync($"User", user);
coming from System.Net.Http.HttpClientExtensions
The code also use many similar methods likes:
Task<HttpResponseMessage> GetAsync(string requestUri);
Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content);
Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content);
Task<HttpResponseMessage> DeleteAsync(string requestUri);
coming from System.Net.Http.HttpClient
But I also need to send value in header (for versioning) so I modified my GetAsync by
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"User/{name}");
request.Headers.Add("ContenT-Type", "application/json;v=2.0");
HttpResponseMessage response = await Client.SendAsync(request);
I don't know if this is correct. Is there a way I can continue to work with get, post, update, postAsJson by setting my header or I'm force to use this generic send version?
I'm not sure, but it appears to me that the default implementation of .NET HttpClient library is flawed. It looks like it sets the Content-Type request value to "text/html" on a PostAsJsonAsync call. I've tried to reset the request value, but not sure if I'm doing this correctly. Any suggestions.
public async Task<string> SendPost(Model model)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync(Url + "api/foo/", model);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
You should set the content type. With the Accept you define what you want as response.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
The Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.
public async Task<string> SendPost(Model model)
{
var client = new HttpClient(); //You should extract this and reuse the same instance multiple times.
var request = new HttpRequestMessage(HttpMethod.Post, Url + "api/foo");
using(var content = new StringContent(Serialize(model), Encoding.UTF8, "application/json"))
{
request.Content = content;
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}