1

I'm calling a WebAPI method from c# code and I'm getting:

the remote server returned an error 403 forbidden

In Local machine it's working perfect and in my deveopment server I am getting 403 forbidden error.

WebClient wc = new WebClient();
string url = string.Empty;
if (Tag == "L") {
    url = ConfigurationSettings.AppSettings["MajraApi"].ToString();
}
var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
wc.UseDefaultCredentials = true;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
    string json1 = "Some JSON String";
    streamWriter.Write(json1);
    streamWriter.Flush();
    streamWriter.Close();
}
httpWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
Isma
  • 14,604
  • 5
  • 37
  • 51
Karthick J
  • 11
  • 1
  • 1
  • 2
  • Is your problem solved ? Feel free to accept the best answer to close topic thks – GGO Jan 12 '18 at 14:35

3 Answers3

1

You probably have set up an authentication to connect to your server iis in production, so you have to define the credentials to allow access to the API. You can't leave the default credentials System.Net.CredentialCache.DefaultCredentials.

Replace the line 14 by this changing userName and password defined in IIS :

httpWebRequest.Proxy.Credentials = new NetworkCredential() {
     UserName = "userName";
     Password = "password";
     Domain = "mydomain"; // facultative
};
GGO
  • 2,678
  • 4
  • 20
  • 42
0

When you send a request with DefaultCredentials, it means the current user, the one who executes the application. In your local machine that is probably your domain user, while on your dev server it is the user set for the app pool - which may not have permissions for the api you try to call.

Miklós Tóth
  • 1,490
  • 13
  • 19
  • Sorry Sir, I can't understand. What can I do this code. – Karthick J Dec 13 '17 at 15:04
  • It seems nothing is wrong with the code, this is a permission issue. So you deploy this c# code to your dev server, and call a web api. Where is this web api and how it authenticates requests? – Miklós Tóth Dec 13 '17 at 15:15
0

Have you set in IIS, Application Pools of your WebApi service .NET CLR version to:

No Managed Code

Also, did u give permissions to your wwwroot of webapi folder to user IIS_IUSRS to Read and Write or even for Modify too (or even Full control) depending of needs. Also add permissions to NETWORK SERVICE.

iis_iusers example

Also check this: IIS_IUSRS and IUSR permissions

Nenad
  • 316
  • 2
  • 14
  • Isn't No Managed Code only for .Net core? https://stackoverflow.com/questions/40862032/iis-application-pools-clr-v4-0-vs-no-managed-code – Codesmith Feb 26 '21 at 02:51