Reputation: 359
this is a first time I'll be using asp.net core so started working on a very simple project to get hands on. The following public API generates a large JSON response of famous quotes. I am trying to query this end point and randomly display one of the quotes.
Here is the code I'm working on
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);
}
}
}
}
While it doesn't show any errors in the code, when I run this code, it says no localhost page found. I'm pretty sure there are 100's of mistake in my code. I tried all over the internet for couple of hours but couldn't find any solution to my problem probably because it is a very simple problem. Thank you for your time!
Upvotes: 0
Views: 930
Reputation: 3857
I've laid out a working (albeit not optimized) example to help step through what you're trying to do. You're creating an HttpClient, but you need to use that client to go query your endpoint; once you have a response, you need to process it into some form you can use and return. The specific endpoint you have also returns a "text/plain" content type.
As you mature your code, you'll want to be careful about overusing HttpClient directly, so reading up on HttpClientFactory would be a good next step.
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; }
}
}
A response will return an OK 200 with content like:
{
"text": "The deepest craving of human nature is the need to be appreciated.",
"author": "William James"
}
Upvotes: 2
Reputation: 124
The question may be simply because there is no static webpage in your current program. So, the true question probably is how to access the api.You could use some tools like swagger or postman.
Remember add UseEndpoints in the Startup
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
If you can't make sure which url to call,adjust the Route property as static like:
Route("api/quote")
And it's highly recommend to add api/ as an apicontroller.
Upvotes: 1