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

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

这是我第一次使用asp.net core,因此开始着手进行一个非常简单的项目。以下公共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个错误。我在互联网上尝试了几个小时,但找不到解决方案,可能是因为这是一个非常简单的问题。感谢您的时间!

c# api asp.net-core random endpoint
1个回答
0
投票

问题可能仅仅是因为您当前的程序中没有静态网页。因此,真正的问题可能是如何访问api。您可以使用一些工具,例如招摇或邮递员。

记住在启动时添加UseEndpoints

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

如果无法确定要调用哪个url,请将Route属性调整为静态,如:

   Route("api/quote")

并且强烈建议将api /添加为apicontroller。

© www.soinside.com 2019 - 2024. All rights reserved.