Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 403禁止。WebException未经.NET处理_C#_Distance_Webrequest_Http Status Code 403 - Fatal编程技术网

C# 403禁止。WebException未经.NET处理

C# 403禁止。WebException未经.NET处理,c#,distance,webrequest,http-status-code-403,C#,Distance,Webrequest,Http Status Code 403,我编写了一个类来计算两个坐标之间的距离。但一旦我运行该项目,就会出现一个错误: WebException未处理 System.Xml.dll中发生类型为“System.Net.WebException”的未处理异常 其他信息:远程服务器返回错误:(403)禁止 我的代码是: public Tuple<double, double> GetCoords(string Streetnumber, string Streetname, string Cityname, string Cou

我编写了一个类来计算两个坐标之间的距离。但一旦我运行该项目,就会出现一个错误:

WebException未处理

System.Xml.dll中发生类型为“System.Net.WebException”的未处理异常

其他信息:远程服务器返回错误:(403)禁止

我的代码是:

public Tuple<double, double> GetCoords(string Streetnumber, string Streetname, string Cityname, string Country)
{
    XmlDocument doc = new XmlDocument();
    string clientId = "///"; =
    string key = "//";
    string address = Streetnumber + "+" + Streetname + ",+" + Cityname + ",+" + Country;

    var urlRequest = "/maps/api/geocode/xml?address=" + address + "&client=" + clientId;
    System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1();
    myhmacsha1.Key = Convert.FromBase64String(key);
    var hash = myhmacsha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(urlRequest));
    string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");
    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

    doc.Load("https://maps.googleapis.com/maps/api/geocode/xml?address=" + address + "&client=" + clientId + "&signature=" + signature);

    string longitude = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lng").InnerText;
    double lng = LongitudePlace(longitude);
    string latitude = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lat").InnerText;
    double lat = LatitudePlace(latitude);
    return Tuple.Create(lng, lat);
}
也许这很容易修复,但我尝试了很多东西。我的
clientID
是正确的,如果我没有弄错的话,它也是console.developer.google.com上的密钥

我尝试了一个测试地址“1600”,“圆形剧场+公园路”,“山+景”,“CA”


如何解决此错误?

您的签名可能格式不正确。具体来说,它缺少URL的一部分。下面是您的代码的编辑版本,使用谷歌提供的代码对URL进行签名。代码可以找到

代码

public Tuple<double, double> GetCoords(string streetNumber, string streetName, string cityName, string country)
{
    XmlDocument doc = new XmlDocument();
    string clientId = "gme-" + "///";
    string key = "//"; //Note this is NOT your API key, it's the Client Secret
    string address = streetNumber + "+" + streetName + ",+" + cityName + ",+" + country;

    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

    doc.Load(Sign("https://maps.googleapis.com/maps/api/geocode/xml?address=" + address + "&client=" + clientId, key));

    string longitude = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lng").InnerText;
    double lng = LongitudePlace(longitude);
    string latitude = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lat").InnerText;
    double lat = LatitudePlace(latitude);
    return Tuple.Create(lng, lat);
}

//From the Google
public static string Sign(string url, string keyString) 
{
    ASCIIEncoding encoding = new ASCIIEncoding();

    // converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
    string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
    byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);

    Uri uri = new Uri(url);
    byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);

    // compute the hash
    HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
    byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);

    // convert the bytes to string and make url-safe by replacing '+' and '/' characters
    string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");

    // Add the signature to the existing URI.
    return uri.Scheme+"://"+uri.Host+uri.LocalPath + uri.Query +"&signature=" + signature;
}
public元组GetCoords(字符串streetNumber、字符串streetName、字符串cityName、字符串country)
{
XmlDocument doc=新的XmlDocument();
字符串clientId=“gme-”+“/”;
string key=“//”;//注意,这不是API密钥,而是客户机机密
字符串地址=街道编号+“+”+街道名称+”,+“+城市名称+”,+“+国家;
WebRequest.DefaultWebProxy.Credentials=CredentialCache.DefaultNetworkCredentials;
单据加载(签名)https://maps.googleapis.com/maps/api/geocode/xml?address=“+address+”&client=“+clientId,key));
字符串经度=doc.SelectSingleNode(“//GeocodeResponse/result/geometry/location/lng”)。InnerText;
双液化天然气=纵向位置(经度);
字符串纬度=doc.SelectSingleNode(“//GeocodeResponse/result/geometry/location/lat”)。InnerText;
双纬度=纬度位置(纬度);
返回Tuple.Create(lng,lat);
}
//来自谷歌
公共静态字符串符号(字符串url、字符串键字符串)
{
ascienceoding encoding=新的ascienceoding();
//将密钥转换为字节将引发异常,需要先替换“-”和“u173”字符。
字符串usablePrivateKey=keyString.Replace(“-”,“+”).Replace(““,“/”);
byte[]privateKeyBytes=Convert.FromBase64String(usablePrivateKey);
Uri=新的Uri(url);
byte[]encodedPathAndQueryBytes=encoding.GetBytes(uri.LocalPath+uri.Query);
//计算散列
HMACSHA1算法=新的HMACSHA1(privateKeyBytes);
byte[]hash=算法.ComputeHash(encodedPathAndQueryBytes);
//将字节转换为字符串,并通过替换“+”和“/”字符使url安全
字符串签名=Convert.ToBase64String(散列)。替换(“+”,“-”)。替换(“/”,“”);
//将签名添加到现有URI。
返回uri.Scheme+“:/”+uri.Host+uri.LocalPath+uri.Query+“&signature=“+signature;
}

可能是您的字符串构建。建议您使用url encode或类似方法您是否将生成的字符串粘贴到浏览器中?@RonBeyer是的,我这样做了,但它不起作用。然后,您生成字符串的方式出现了问题,与代码没有任何关系。我会查找API示例,找出您的请求字符串错误的地方。既然你得到了403,我就从密钥或你的客户端ID开始。你检查过API规范以确保你传递了正确的参数吗?当我仅使用正确工作的地址()测试URL时,仍然无法工作,在doc.Load(符号(“+address+”&client=“+clientId,key))处出现相同的错误;您是否将
gme-
放在您的客户ID之前?@amura.csg否,我的客户ID以数字开头,以字母结尾,以.apps.googleusercontent.com结尾。当我测试一些代码时,我正在使用这些代码查看签名是否正确。我注意到的一件事是,如果我从我的客户ID离开
gme-
,这将表明我的客户选项缺失。您的URL应该类似于
https://maps.googleapis.com/maps/api/geocode/xml?address=&client=gme-numbers stuff.apps.googleusercontent.com
仍然无法工作。。这很奇怪。第一次出现这样的情况,并且在尝试修复后无法正常工作。
public Tuple<double, double> GetCoords(string streetNumber, string streetName, string cityName, string country)
{
    XmlDocument doc = new XmlDocument();
    string clientId = "gme-" + "///";
    string key = "//"; //Note this is NOT your API key, it's the Client Secret
    string address = streetNumber + "+" + streetName + ",+" + cityName + ",+" + country;

    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

    doc.Load(Sign("https://maps.googleapis.com/maps/api/geocode/xml?address=" + address + "&client=" + clientId, key));

    string longitude = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lng").InnerText;
    double lng = LongitudePlace(longitude);
    string latitude = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lat").InnerText;
    double lat = LatitudePlace(latitude);
    return Tuple.Create(lng, lat);
}

//From the Google
public static string Sign(string url, string keyString) 
{
    ASCIIEncoding encoding = new ASCIIEncoding();

    // converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
    string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
    byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);

    Uri uri = new Uri(url);
    byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);

    // compute the hash
    HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
    byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);

    // convert the bytes to string and make url-safe by replacing '+' and '/' characters
    string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");

    // Add the signature to the existing URI.
    return uri.Scheme+"://"+uri.Host+uri.LocalPath + uri.Query +"&signature=" + signature;
}