为什么运行此任务返回错误:System.Net.Http.HttpRequestException:响应状态代码不指示成功:404(未找到)

问题描述 投票:0回答:1

作为一个业余项目,我决定制作一个不和谐的机器人,允许用户输入单词并获取其定义。除了实际获取定义的命令之外,我已经完成了大部分事情。我正在使用 FreeDictionaryAPI,当我运行时

public class DictionaryCommand : BaseCommandModule
{
    [Command("dict")]
    public async Task dictCommand(CommandContext ctx)
    {
        //await ctx.Channel.SendMessageAsync("Penis");

        var dictionary = new DictionaryOutput();
        await dictionary.getDefinition(ctx.Message.Content);
        await ctx.Channel.SendMessageAsync(dictionary.defo); 
    }
}

理论上它应该运行

public async Task getDefinition(string message)
{
    //Dictionary stuff
    string DictionaryURL = "https://api.dictionaryapi.dev/api/v2/entries/en/" + message;

    using (var client = new HttpClient())
    {
        try
        {
            var response = await client.GetStringAsync(DictionaryURL);
            List<Word>? word = JsonSerializer.Deserialize<List<Word>>(response.ToString());
            Console.WriteLine(word);

            defo = word[0].meanings[0].definitions[0].definition;
        }
        catch (HttpRequestException exception)
        {
            Console.WriteLine("Error: {0}", exception);
        }
    }
}

然而,它又回来了

Error: System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.HttpClient.GetStringAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at DictionaryAPITesting.DictionaryOutput.getDefinition(String message) C:\repos\DictionaryAPITesting\DictionaryAPITesting\DictionaryOutput.cs:line 18

第 18 行是包含

var response = await client.GetStringAsync(DictionaryURL);

的行

当方法为

.GetAsync
时工作正常,但切换到
.GetStringAsync

时就中断了

到目前为止,我尝试简单地使用

.GetAsync
方法而不是
.GetStringAsync
方法,但在整个程序决定不运行之后,这已被证明是徒劳的。到目前为止,这确实是我尝试过的唯一方法,因为我真的不知道问题是什么。有办法解决这个问题吗?

c# dotnet-httpclient dsharp+
1个回答
0
投票

基于此文档,从用户处获取参数的命令(在您的情况下是一个单词)需要在方法签名中使用实际的字符串参数

我的答案只是从 HTTP 响应中返回字符串,但您可以做任何您想做的事情,例如将其反序列化为

Word
对象。使用
GetStringAsync
GetAsync
并不重要,重要的是你正确处理了404 Not Found

因为,如果 URL 尝试查找不存在的单词,API 会回复 404 Not Found 状态,并包含以下正文:

{"title":"No Definitions Found","message":"Sorry pal, we couldn't find definitions for the word you were looking for.","resolution":"You can try the search again at later time or head to the web instead."}

可能的实现:

[Command("dict")]
public async Task DictCommand(CommandContext ctx, string word)
{
    var dictionary = new DictionaryOutput();
    string definition = await dictionary.getDefinition(word);
    // await ctx.Channel.SendMessageAsync(dictionary.defo); 
    await ctx.RespondAsync($"Definition for {word}: {definition}");
}


public async Task<string> GetDefinition(string message)
{
    //Dictionary stuff
    string DictionaryURL = "https://api.dictionaryapi.dev/api/v2/entries/en/" + message;


    using (var client = new HttpClient())
    {
        try
        {
            var response = await client.GetAsync(DictionaryURL);
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsStringAsync();
            else 
                return $"Word '{message}' not found in dictionary!";
            // List<Word> word = JsonSerializer.Deserialize<List<Word>>(response.ToString());
        }
        catch (HttpRequestException exception)
        {
            Console.WriteLine("Error: {0}", exception);
        }
    }
    return null;
}
© www.soinside.com 2019 - 2024. All rights reserved.