0

How can do I work with StackOverflow API and HTTP request it?

This is my problem: I want to get first 1000 tags from Stack Exchange API, see their popularity and usage.

This is what I've done so far:

  1. Created an ASP.NET MVC project

  2. Added HTTP Client in Startup.cs file:

     public void ConfigureServices(IServiceCollection services)
     {
         services.AddControllersWithViews();
         services.AddHttpClient("stackoverflow", s =>
         {
             s.BaseAddress = new Uri("https://api.stackexchange.com/2.3");
             s.DefaultRequestHeaders.Add("client_id", "1");
             s.DefaultRequestHeaders.Add("site", "stackoverflow");
             s.DefaultRequestHeaders.Add("redirect_uri", "https://api.stackexchange.com/2.3/tags?");
         });
     }
    
  3. Created classes Tags and interface ITagsRepository:

     public class Tags
     {
         public int Id { get; set; }
         public int Popularity { get; set; }
         public decimal Usage { get; set; }
     }
    
     public class TagsRepository : ITagsRepository
     {
         public Tags GetTag(int id)
         {
             // put logic in here
         }
     }
    
  4. I also have added a TagsController in HomeController.cs:

     public class TagsController : Tags
     {
         private ITagsRepository _tagsRepository;
    
         public TagsController(ITagsRepository tagsRepository)
         {
             _tagsRepository = tagsRepository;
         }
    
         public IActionResult GetTag(int id)
         {
             Tags tag = _tagsRepository.GetTag(id);
             return View(tag);
         }
     }
    

My question is: how do I make my code run in index.cshtml and how do I make http requests that are customisable from client side?

2
  • I have voted to close as duplicate of Dependency injection: HttpClient or HttpClientFactory? as the first obstacle, although not the only one, is to get the HttpClient registered in startup into your repository class. The accepted answer explains how to do that. (What you have is a "named client"). Commented Nov 6, 2021 at 11:51
  • N.b. TagsController doesn't need to inherit from Tags, so remove that. I don't think it will cause a problem, it just doesn't make any sense. Commented Nov 6, 2021 at 11:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.