I\'ve written an app that has worked fine for months, in the last few days I\'ve been getting the error below on the installed version only.
If I run the source code
In my case, I had to call an API repeatedly in a loop, which resulted in halt of my system returning a 403 Forbidden Error
. Since my API provider does not allow multiple requests from the same client within milliseconds, I had to use a delay of 1 second at least :
foreach (var it in list)
{
Thread.Sleep(1000);
// Call API
}
Add the following line:
request.UseDefaultCredentials = true;
This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.
It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
Hope this helps.
In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.
[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
$req.UserAgent = "BlackHole"
$req.UseDefaultCredentials = $true
private class GoogleShortenedURLResponse
{
public string id { get; set; }
public string kind { get; set; }
public string longUrl { get; set; }
}
private class GoogleShortenedURLRequest
{
public string longUrl { get; set; }
}
public ActionResult Index1()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ShortenURL(string longurl)
{
string googReturnedJson = string.Empty;
JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
GoogleShortenedURLRequest googSentJson = new GoogleShortenedURLRequest();
googSentJson.longUrl = longurl;
string jsonData = javascriptSerializer.Serialize(googSentJson);
byte[] bytebuffer = Encoding.UTF8.GetBytes(jsonData);
WebRequest webreq = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
webreq.Method = WebRequestMethods.Http.Post;
webreq.ContentLength = bytebuffer.Length;
webreq.ContentType = "application/json";
using (Stream stream = webreq.GetRequestStream())
{
stream.Write(bytebuffer, 0, bytebuffer.Length);
stream.Close();
}
using (HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse())
{
using (Stream dataStream = webresp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
googReturnedJson = reader.ReadToEnd();
}
}
}
//GoogleShortenedURLResponse googUrl = javascriptSerializer.Deserialize<googleshortenedurlresponse>(googReturnedJson);
//ViewBag.ShortenedUrl = googUrl.id;
return View();
}