为什么我在连接到 Text Analytics API 时收到 (400) Bad Request 错误?

Why am I getting (400) Bad Request error when connecting to Text Analytics API?

我是新的 C# 开发人员,我正在尝试在我的测试 ASP.NET 应用程序中使用文本分析 API 和 Azure 机器学习来定义我在数据库。 我按照这篇有用的文章 over here 进行操作,以便能够连接到文本分析 API。在调试我的代码时,我能够获得列表中第一条推文的关键短语和情绪,然后出现以下异常,我不知道为什么:

The remote server returned an error: (400) Bad Request.

这是我的代码:

private const string apiKey = "XXXXXXXXX"; //Key 2 value of Text Analytics API from Azure Portal
        private const string sentimentUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
        private const string keyPhrasesUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases";
        private const string languageUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages";

        protected void Page_Load(object sender, EventArgs e)
        {

        }


        private IEnumerable<T_Tweet> GetData()
        {
            TweetBL tweetBl = new TweetBL();
            IEnumerable<T_Tweet> tweetsList = tweetBl.GetTweets();
            return tweetsList;
        }


        protected void lbtnAnalyze_Click(object sender, EventArgs e)
        {
            var tweetsList = GetData();
            if (tweetsList != null)
            {
                List<TweetSentimentModel> tweetSenti = new List<TweetSentimentModel>();
                foreach (var tweet in tweetsList)
                {
                    try
                    {
                        // Prepare headers
                        var client = new WebClient();
                        client.Headers.Add("Ocp-Apim-Subscription-Key", apiKey);
                        client.Headers.Add("Content-Type", "application/json");
                        client.Headers.Add("Accept", "application/json");

                        // Detect language
                        var postData1 = @"{""documents"":[{""id"":""1"", ""text"":""@sampleText""}]}".Replace("@sampleText", tweet.TweetText);
                        var response1 = client.UploadString(languageUri, postData1);
                        var language = new Regex(@"""iso6391Name"":""(\w+)""").Match(response1).Groups[1].Value;

                        // Determine sentiment
                        var postData2 = @"{""documents"":[{""id"":""1"", ""language"":""@language"", ""text"":""@sampleText""}]}".Replace("@sampleText", tweet.TweetText).Replace("@language", language);
                        var response2 = client.UploadString(sentimentUri, postData2);
                        var sentimentStr = new Regex(@"""score"":([\d.]+)").Match(response2).Groups[1].Value;
                        var sentiment = Convert.ToDouble(sentimentStr, System.Globalization.CultureInfo.InvariantCulture);

                        // Detemine key phrases
                        var postData3 = postData2;
                        var response3 = client.UploadString(keyPhrasesUri, postData2);
                        var keyPhrases = new Regex(@"""keyPhrases"":(\[[^\]]*\])").Match(response3).Groups[1].Value;


                        TweetSentimentModel tweetSentiObj = new TweetSentimentModel();
                        tweetSentiObj.TweetId = tweet.Id;
                        tweetSentiObj.TweetText = tweet.TweetText;
                        tweetSentiObj.SentimentLabel = sentiment.ToString();
                        tweetSentiObj.KeyPhrases = keyPhrases;
                        tweetSentiObj.CreatedOn = DateTime.Now;
                        tweetSenti.Add(tweetSentiObj);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                if (tweetSenti != null)
                {
                    PrintAnalysisResults(tweetSenti);
                }
            }
        }

你能告诉我为什么会出现这个错误以及我该如何解决它吗?

I was able to get the key phrases and sentiment for the first tweet in the list and then I got the following exception and I don't know why:

根据您的描述,第二次和第一次的区别在于tweet对象。而(400) Bad Request也意味着http请求客户端参数不正确。

我可以在 tweet.TweetText 等于 null 或 tweet.TweetText.trim() 等于 string.empty 时复制它。

请尝试调试,如果是这种情况,请尝试添加逻辑来控制它。以下是演示代码。

if (!string.IsNullOrEmpty(tweet.TweetText?.Trim()))
  {
       // Determine sentiment
       var postData2 = @"{""documents"":[{""id"":""1"", ""language"":""@language"", ""text"":""@sampleText""}]}".Replace(
                            "@sampleText", tweet.TweetText).Replace("@language", language);
                    var response2 = client.UploadString(SentimentUri, postData2);
                    var sentimentStr = new Regex(@"""score"":([\d.]+)").Match(response2).Groups[1].Value;
                    var sentiment = Convert.ToDouble(sentimentStr, System.Globalization.CultureInfo.InvariantCulture);

                    // Detemine key phrases
                    var postData3 = postData2;
                    var response3 = client.UploadString(KeyPhrasesUri, postData2);
                    var keyPhrases = new Regex(@"""keyPhrases"":(\[[^\]]*\])").Match(response3).Groups[1].Value;

    }