I am trying to use the HttpClient to access a REST service which requires NTLM authentication. However I keep getting a 401 Unauthorized.
My code looks like this
private static void Main()
{
var uri = new Uri("http://localhost:15001");
var credentialsCache = new CredentialCache { { uri, "NTLM", CredentialCache.DefaultNetworkCredentials } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
var httpClient = new HttpClient(handler) { BaseAddress = uri, Timeout = new TimeSpan(0, 0, 10) };
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = httpClient.GetAsync("api/MyMethod").Result;
}
My target framework is netcoreapp2.0. If I change to net461, it will work. Not sure what I am doing wrong?
Microsoft has accepted this as a bug. Possibly a fix will be released with core 2.1
https://github.com/dotnet/corefx/issues/25988
Related
I'm trying to request data over HTTP 2.0. I'm using the HttpClient from .Net 5. I'm on Windows 10. The problem is that the version on the response seems to always be "1.1". What am I doing wrong here?
var httpClient = new HttpClient();
string authToken = "{jwt token}";
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
var req = new HttpRequestMessage(HttpMethod.Get, "{url}")
{
Version = new Version(2, 0)
};
var x = httpClient.SendAsync(req).ConfigureAwait(false).GetAwaiter().GetResult();
var version = x.Version;
Console.WriteLine(version);
//request init
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(client.BaseAddress + ""),
Content = jsonContent
};
Console.WriteLine(request.Method);
var response = await client.SendAsync(request);
Console.WriteLine(response.RequestMessage);
The Request message shows that it was sent as GET, even though I set Method to Post
I think your endpoint is doing a redirect, try turning that off via the HttpClientHandler.
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
var client = new HttpClient(handler);
// Do your work.
your code is doing the right thing. here's a console app that does the same thing, and the outcome is the right one. an Https POST call is done to the configured URL.
using System;
using System.Net.Http;
namespace testapicall
{
class Program
{
static void Main(string[] args)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://google.com")
};
Console.WriteLine(request.Method);
var response = client.SendAsync(request).GetAwaiter().GetResult();
Console.WriteLine(response.RequestMessage);
}
}
}
and here's the console log output: Method: POST, RequestUri: https://google.com/', Version: 1.1, Content: , Headers:{}
what is the resource behind the URL you're trying to call doing? Maybe it is redirecting to another resource, by doing a GET request.
I recommend to use the RestClient to execute the Rest APIs.
Please refer the following URL and sample code
https://restsharp.dev/
var client = new RestClient("URL");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("parameter name", "values");
IRestResponse response = client.Execute(request);
var data = (JObject)JsonConvert.DeserializeObject(response.Content);
I'm experiencing an intermittent problem with our SharePoint 2010 REST API. I have a .Net Core Console application that makes a series of calls to SharePoint List Endpoints to get a JSON response. My problem is that at random times, the API response is an error page:
A relative URI cannot be created because the 'uriString' parameter
represents an absolute URI.http://www.example.com/somefolder/file.svc
Is there a problem with my HTTPClient configuration? Is there a configuration setting that I can toggle in SharePoint to prevent the error or more reliable?
var uri = new Uri("http://www.example.com/");
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient Client = new HttpClient(handler);
Client.BaseAddress = new Uri("http://www.example.com/sharepoint/path/ListData.svc/");
// Make the list request
var result = await Client.GetAsync("MySharePointList");
To get the list items, the REST API URI like below.
http://sp2010/_vti_bin/ListData.svc/listname
Modify the code as below.
var siteUrl = "http://www.example.com/";
var listName = "MySharePointList";
var uri = new Uri(siteUrl);
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(uri, "/_vti_bin/ListData.svc");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
var requestURL = siteUrl + "/_vti_bin/ListData.svc/" + listName;
// Make the list request
var result = client.GetAsync(requestURL).Result;
var items= result.Content.ReadAsStringAsync();
I am trying to pull REST data from an API but I need to handle the calls to the API with some server side solution. I have tried using the following code
try
{
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(60);
var request = new HttpRequestMessage()
{
RequestUri = new Uri(string.Format("https://jsonodds.com/{0}{1}{2}", "api/odds/", "?source=", "3")),
Method = HttpMethod.Get,
};
request.Headers.Add("JsonOdds-API-Key", "your key");
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
String.Format("Success");
}
}
catch (Exception ex)
{ //log error }
I receive a 407() error. Any ideas or tips how to do this?
If you are going through a proxy server then you need to use a different constructor for HttpClient.
_httpClient = new HttpClient(new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Address = new Uri(proxyUrl),
BypassProxyOnLocal = false,
UseDefaultCredentials = true
}
})
{
BaseAddress = url
};
Replace proxyUrl with your proxy address then replacing the credential with those that are valid for your proxy. This example uses the default credentials, but you can pass a NetworkCredential to the WebProxy.
I am using the HttpClient class to make GET requests, it works perfectly without proxy, but when I try to make a request thought a proxy server, it adds hostname in the path and there is also hostname in headers, so the full url is like http://google.comhttp://google.com/
The code:
static void GetSmth()
{
var baseAddr = new Uri("http://google.com");
var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
UseCookies = true,
UseProxy = true,
Proxy = new WebProxy("111.56.13.168:80", true),
};
HttpClient client = new HttpClient(handler);
client.BaseAddress = baseAddr;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/");
var resp = client.SendAsync(request).Result;
}
Wireshark screenshot:
What is wrong with it?