Home > Mobile >  How to create a basic web api to get data
How to create a basic web api to get data

Time:01-08

Trying to create a basic web api for my database table where anyone can view my table data using a URL (JSON format?). My understanding is that I should be able to get my data by typing in table name in URL.

my database table name is myTable which is mapped to model class My_Model

Issue: There are no errors but when i try to type in url https://localhost:7048/myTable/ it return page not found

[Route("[controller]")]
[ApiController]
public class My_Controller : Controller
{
    public My_Services _services { get; }

    public My_Controller(My_Services services)
    {
        this._services = services;
    }

    // Database Table Name = "myTable"
    [HttpGet]
    public IQueryable<My_Model> Get()
    {

        return (IQueryable<My_Model>)_services.Get_All_Data();
    }

    public IActionResult Index()
    {
        return View();
    }
}

My_Services class - where get all data from table

    public async Task<IQueryable<My_Model>> Get_All_Data()
    {
        IQueryable<My_Model> Query = from x in _context.My_DbSet
                             select x;
        return Query;
    }

CodePudding user response:

My understanding is that I should be able to get my data by typing in table name in URL.

No, this is not how it works. You should check Routing to controller actions in ASP.NET Core. In your example you should be able to access your data using this url: https://localhost:7048/My_. The reason is that your controller has the attribute [Route("[controller]")]. [controller] is a special value which means that the route should be the controller class name without the Controller suffix so My_ in this case.

If you want to have access using this url: https://localhost:7048/myTable then you need to either change the attribute to this: [Route("myTable")] or to change the controller class name to MyTableController.

Also your Get method looks wrong. You should await the _services.Get_All_Data method instead of casting to IQueryable<My_Model>:

[HttpGet]
public async Task<IQueryable<My_Model>> Get()
{
    return await _services.Get_All_Data();
} 
  • Related