I am calling a simple Web Api service using HTTPClient. The service accepts a parameter, like URL and saves it in a SQL table, converts that url to guid and returns it back to the caller. The code below is used inside a SharePoint Web part which is called via a button click event handler.
public void DisplayUrl(string host,string paramUrl)
{
string longUrl = string.Format("https://{0}-UrlApi/AddUrl?longUrl={1}", host,paramUrl);
var result = GetUrl(longUrl).GetAwaiter().GetResult();
tboxResults.Text = result.ShortUrl;
}
protected static async Task<ShortUrlResponse> GetUrl(string baseUrl)
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
using (var client = new HttpClient(handler))
{
var response = client.GetAsync(baseUrl).Result;
if (response.IsSuccessStatusCode)
{
HttpResponseMessage response1 = response;
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ShortUrlResponse>(resp);
return result;
}
return null;
}
}
The web part is deployed to testing environment and when I open the page in the browser from a machine outside test server I get this error. At one point I was getting it inside the test server as well, but after I clicked the button a second time it worked correctly, but not in the dev machine for example.
This is the error that I am getting.
Error message: One or more errors occurred.
InnerException: System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized. ---> System.ComponentModel.Win32Exception: The logon attempt failed at System.Net.NTAuthentication.GetOutgoingBlob(Byte[] incomingBlob, Boolean throwOnError, SecurityStatus& statusCode) at System.Net.NTAuthentication.GetOutgoingBlob(String incomingBlob) at System.Net.NegotiateClient.DoAuthenticate(String challenge, WebRequest webRequest, ICredentials credentials, Boolean preAuthenticate) at System.Net.NegotiateClient.Authenticate(String challenge, WebRequest webRequest, ICredentials credentials) at System.Net.AuthenticationManagerDefault.Authenticate(String challenge, WebRequest request, ICredentials credentials) at System.Net.AuthenticationState.AttemptAuthenticate(HttpWebRequest httpWebRequest, ICredentials authInfo) at System.Net.HttpWebRequest.CheckResubmitForAuth() at System.Net.HttpWebRequest.CheckResubmit(Exception& e, Boolean& disableUpload) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) --- End of inner exception stack traceStackTrace:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
TUrlControl:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at AIntranet.WebParts.TUrl.TUrlUserControl.d__3.MoveNext()End of stack trace from previous location where exception was thrown
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at AIntranet.WebParts.TUrl.TUrlUserControl.DisplayUrl(String host, String paramUrl)
at AIntranet.WebParts.TUrl.TUrlUserControl.b__1_0()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at AIntranet.WebParts.TUrl.TUrlUserControl.btnTUrl_Click(Object sender, EventArgs e)