简体   繁体   中英

EXE program calling aspx page gets: 401 - Unauthorized: Access is denied due to invalid credentials

I'm creating an executable program that uses HttpClient to call a URL. I try using the DefaultNetworkCredentials as I do not know the user id and password of the server. The following code runs successfully on my local machine, but it will get error when deployed to the server.

在此处输入图片说明

My code:

HttpClientHandler authtHandler = new HttpClientHandler()
{
    Credentials = CredentialCache.DefaultNetworkCredentials
};

// Call the URL                    
using (HttpClient httpClient = new HttpClient(authtHandler))
{
    var formContent = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("testingkey", "testingvalue")
    });

    // Make it sync instead of async by using .Result
    var result = httpClient.PostAsync(url, formContent).Result;

    // Get the content, for verification 
    var content = result.Content;
}

DefaultNetworkCredentials is the authentication credentials for the current security context in which the application is running. For client side application, these are usually the Windows credentials of the user who is running the application.

If the user does not have rights over the URL over what you are using the HttpClient then error will come. To make it work you

  1. either have to impersonate the user who has access over that application or
  2. run your EXE using system defined accounts like Network Service credentials and ensure that HTTP application can be accessed using the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM