I am working on a ASP.NET Web Api and I'm having an issue figuring out how to display data to the api.
So to explain what I need to figure out. After accessing the objects from the Json file and converting JSON to a .NET type. I believe I should be able to display these on the api?
For example, whatever field I ask for, it should return the result sorted by that field. Now I need to display this data in different ports. For example.
- https://host:port/api/books returns all unsorted (Book1-Book13)
- https://host:port/api/books/id returns all sorted by id (Book1-Book13)
- https://host:port/api/books/id/1 returns all with id containing '1' sorted by id (Book1, Book10-13)
I have followed this tutorial by microsoft and the application seems to be working in regards to starting and using different ports.
This is the code I have set up in my controller class BooksController.cs
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
[HttpGet]
public ActionResult GetAllBooks()
{
string[] books = { "book1", "book2", "book3" };
if (!books.Any())
return NotFound();
return Ok(books);
}
[HttpGet("id/{id}")]
public string GetBookById(int id)
{
return $"book: {id}";
}
[HttpGet("author/{author}")]
public string GetBookByAuthor(string author)
{
return $"author: {author}";
}
This is my startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
GetAllBooks();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public void GetAllBooks()
{
string _path = $"C:\\Users\\filip\\source\\repos\\NexerGroupApi\\NexerGroupApi\\books.json";
string jsonFromFile;
using (var reader = new StreamReader(_path))
{
jsonFromFile = reader.ReadToEnd();
}
var booksFromJsonFile = JsonConvert.DeserializeObject<List<NexerGroupApi.Book>>(jsonFromFile);
JArray bookArray = JArray.FromObject(booksFromJsonFile);
IList<Book> bookList= bookArray.Select(p => new Book
{
Id = (string)p["Id"],
Author = (string)p["Author"],
Title = (string)p["Title"],
Genre = (string)p["Genre"],
Price = (string)p["Price"],
Publish_date = (string)p["Publish_date"],
Description = (string)p["Description"]
}).ToList();
}
public class Book
{
public string Id { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
public string Price { get; set; }
public string Publish_date { get; set; }
public string Description { get; set; }
}
I wonder where I actually set up my GetAllBooks() method so that I can then access them in the BooksController.cs and be able to do api/books/bookNameFromJsonFile and show that specific object with all of it's contents such as id, author, title, genre, etc.
I know that my IList<Book> bookList in the class startup.cs does not work, for some reason every variable get's null value. Although not sure why.
/api/books/1, it doesn't know whether1is an Id or an Author. For GetBookByAuthor, you might change it to[HttpGet("author/{author}")], then someone who wished to look up books by author would hit the URL/api/books/author/Tom%20Clancy, and change GetBookById to[HttpGet("id/{id}")]so they can hit the URL/api/books/id/1. That makes it unambiguous. Just put some thought into how your structure the routes.