ASP.Net CORE 请求端点并从端点解析随机字符串

ASP.Net CORE request an endpoint and parse random string from the endpoint

这是我第一次使用 asp.net 核心,因此开始着手一个非常简单的项目来上手。 以下 public API 生成大量 JSON 名言回应。我正在尝试查询此端点并随机显示其中一个引号。

https://type.fit/api/quotes

这是我正在处理的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net.Http;

     namespace QuoteAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class QuoteGenerator : ControllerBase
{
    [HttpGet]
    public static char Main()
    {
        string quotations = "https://type.fit/api/quotes";
        using (HttpClient client = new HttpClient())
        {
            Random rand = new Random();
            int r = rand.Next(quotations.Length);
            var quotation = quotations[r];
            return quotation;       

            // return  await client.GetStringAsync(quotations);
        }
    }


   }


 }

虽然代码中没有显示任何错误,但当我 运行 这段代码时,它说找不到本地主机页面。我很确定我的代码中有 100 个错误。我在互联网上尝试了几个小时,但找不到任何解决我的问题的方法,可能是因为这是一个非常简单的问题。感谢您的时间!

这个问题可能只是因为你当前的程序中没有静态网页。 所以,真正的问题可能是如何访问 api.You 可以使用一些工具,比如 招摇或邮递员。

记得在Startup中添加UseEndpoints

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

如果您不能确定调用哪个 url,请将路由 属性 调整为静态,如:

   Route("api/quote")

强烈建议添加 api/ 作为 api 控制器。

我列出了一个有效的(尽管未优化)示例来帮助逐步完成您正在尝试做的事情。您正在创建一个 HttpClient,但您需要使用该客户端来查询您的端点;收到回复后,您需要将其处理成某种可以使用的形式 return。您拥有的特定端点还 return 是 "text/plain" 内容类型。

随着代码的成熟,您需要小心不要直接过度使用 HttpClient,因此继续阅读 HttpClientFactory 将是一个很好的下一步。

namespace WebApplication.Controllers
{
    [Route("[controller]")]
    public class QuoteController : ControllerBase
    {
        public QuoteController()
        {
        }

        // By making this asynchronous, we can let our potentially long-running HttpClient calls let up some resources
        [HttpGet]
        public async Task<ActionResult<Quote>> GetQuote()
        {
            using(HttpClient client = new HttpClient())
            {
                var result = await client.GetAsync("https://type.fit/api/quotes");  // Perform a GET call against your endpoint asynchronously
                if (result.IsSuccessStatusCode)     // Check that the request returned successfully before we proceed
                {
                    var quoteListString = await result.Content.ReadAsStringAsync();     // Your endpoint returns text/plain, not JSON, so we'll grab the string...
                    var quoteList = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Quote>>(quoteListString);     // ... and can use Newtonsoft (or System.Text.Json) to deserialize it into a list we can manipulate.
                    return quoteList.ElementAt(new Random().Next(0, quoteList.Count() - 1));  // Now we have an enumeration of quotes, so we can return a random element somewhere between index 0 and the count of entries minus 1
                }
                else
                {
                    return NotFound();  // But if the call didn't find anything, return a 404 instead
                }
            }
        }
    }

    // A strongly typed class helps us receive and manipulate our data
    public class Quote
    {
        public string Text { get; set; }
        public string Author { get; set; }
    }
}

回复将 return OK 200,内容如下:

{
  "text": "The deepest craving of human nature is the need to be appreciated.",
  "author": "William James"
}