【问题标题】:IIS asp.net C# API Post Method error "'The remote server returned an error: (403) Forbidden.'"IIS asp.net C# API Post Method 错误“'远程服务器返回错误:(403) Forbidden.'”
【发布时间】:2021-01-22 05:03:50
【问题描述】:

我通过 gupshup 创建了一个 viber 机器人。我在 win 10 中使用 IIS 服务器运行我的 WebForm 应用程序。我尝试通过 api post 方法向我的 viberbot 发送消息,但 c# 扼杀了我。(我成功测试了 url 和参数)

这是我的代码:

protected void viber_msg(String viberid, String strmsg)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.gupshup.io/sm/api/bot/mybotname/msg?apikey=mykey");
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.Method = "POST";

   
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "context={'botname':'mybotname','channeltype':'viber','contextid':'viberid','contexttype':'p2p'}&message="+strmsg;
        streamWriter.Write(json);
    }
    
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    viber_msg("viberuserID", "This is a message");
}

我得到的错误是“System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'” 还尝试使用 POSTMAN 并获取 "message": "Invalid authentication credentials" 提前谢谢...

【问题讨论】:

  • 我觉得你有两个问题 1) c# 代码 2) 密钥错误的邮递员。 apikey=mykey 首先让 Postman 工作,这比 c# 更容易。当使用 https 发出请求时,TLS 用于身份验证。由于使用了 TLS 版本,c# 失败。 Postman 正在通过 TLS 身份验证,但由于 id 错误而失败。
  • 我的 apikey 没问题。我在 java programm(eclipse) 中使用相同的 url。上下文也正确。
  • 使用像wireshark或fiddler这样的嗅探器并比较eclipse和Postman之间的第一个请求,看看为什么Postman会失败。还要比较 eclipse 和 c# 中的 TLS 版本,看看 TLS 版本的区别。您最后一次使用 eclipse 应用程序是什么时候? TLS 1.0/1.1 不再起作用,旧代码可能无法正常工作。
  • 我成功地与邮递员一起发帖,只需为我的 gupshup 帐户添加 2 个新参数 userId 和密码。我试图在 C# 中添加但失败了。 "api.gupshup.io/sm/api/bot/botname/…"
  • 在您的 WebRequest 之前在 c# 中添加: System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 如果 Tls12 不起作用,请尝试 Tls13。

标签: c# api iis gupshup


【解决方案1】:
protected void viber_msg(String viberid, String message)
{
    var client = new RestClient("https://api.gupshup.io/sm/api/bot/mybot/msg?apikey=myapikey");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    request.AddParameter("context", "{\"botname\": \"mybot\",\"channeltype\" :\"viber\",\"contextid\": \""+viberid+"\",\"contexttype\": \"p2p\"}");
    request.AddParameter("message", message);
    IRestResponse response = client.Execute(request);
} 

protected void Button1_Click(object sender, EventArgs e)
{
    viber_msg("viberid", "message");
}

}

RestSharp 库!!!

【讨论】:

  • 如果您的问题得到解决,那么我请求您将有用的建议标记为答案。这将帮助面临同样问题的其他人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多