Search code examples
c#asp.netasp.net-coreasp.net-web-apirazor

How to call an ASP.NET API in an ASP.NET Razor web application


I'm building an ASP.NET Core 6 web app with Razor Pages and an ASP.NET API with a Mongo database. I have the API and it returns the correct data in Json, however I can't figure out how to call this in the web app and display the data on a Razor page. This is the code i have so far but every time i run this I get this exception

Cannot assign requested address (localhost:52189)

This is the code I have in the controller class

public class IncidentController : Controller
{
    private static readonly String conn = "https://localhost:52189/api/incident/";

    public static async Task<List<IncidentModel>> Index()
    {
        List<IncidentModel> incidents = new List<IncidentModel>();

        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(conn))
            {
                string apiResponse = await response.Content.ReadAsStringAsync();
                incidents = JsonConvert.DeserializeObject<List<IncidentModel>>(apiResponse);
            }
        }

        return incidents;
    }
}

And then the Razor page (index.cshtml.cs)

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    public dynamic incidentList;

    public IndexModel(ILogger<IndexModel> logger)   
    {
        _logger = logger;
        GetIncidents();
    }

    public async void GetIncidents()
    {
        this.incidentList = await IncidentController.Index();
    }
}

Basically, how can I correctly call this API and display the data on the index.cshtml page? Any help or tutorials links will be greatly appreciated.


Solution

  • call this in the web app and display the data on a Razor page

    In your IndexModel, change code like below, then you can call an ASP.NET API in an ASP.NET Razor and get the json :

    public  async Task<JsonResult> OnGetIncidentsAsync()
            {
                List<IncidentModel> incidents = new List<IncidentModel>();
                using (var httpClient = new HttpClient())
                {              
                    using (HttpResponseMessage response = await httpClient.GetAsync("https://localhost:52189/api/incident/"))
                    {                   
                        string apiResponse = await response.Content.ReadAsStringAsync();
                        incidents =JsonConvert.DeserializeObject<List<IncidentModel>>(apiResponse);                   
                    }
                }
                return new JsonResult(incidents);
            }
    

    Besides below is work demo(show the list of cars in the Index.cshtml) about display the data on a Razor page, you can refer to it:

    Car

     public class Car
        {
            public int Id { get; set; }
            public string Make { get; set; }
            public string Model { get; set; }
            public int Year { get; set; }
            public int Doors { get; set; }
            public string Colour { get; set; }
            public decimal Price { get; set; }
        }
    

    IndexModel

    public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
    
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
    
            public  async Task<JsonResult> OnGetIncidentsAsync()
            {
                List<Car> incidents = new List<Car>();
                using (var httpClient = new HttpClient())
                {              
                    using (HttpResponseMessage response = await httpClient.GetAsync("https://localhost:44300/api/Car"))
                    {                   
                        string apiResponse = await response.Content.ReadAsStringAsync();
                        incidents =JsonConvert.DeserializeObject<List<Car>>(apiResponse);                   
                    }
                }
                return new JsonResult(incidents);
            }
        }
    

    Index.cshtml:

    @page "{handler?}"
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
      @section scripts{
    <script type="text/javascript">
        $(function () {
            $.get('/Index/Incidents').done(function (cars) {
                $.each(cars, function (i, car) {
                    var item = `<li>
                                <strong>${car.make} ${car.model}</strong>
                                (£${car.price})</li>`;
                    $('#car-list').append(item);
                });
            });
        });
    </script>
    }
    

    Result:

    enter image description here