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

Time:06-10

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.

CodePudding user response:

You can call an API end point using httpClient Here is the code.

  public async Task<List<IncidentModel>> GetRequestAsync()
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
    
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("Key","Value");

                    using (HttpResponseMessage response = await httpClient.GetAsync("https://localhost:52189/api/incident"))
                    {
                        if (response.IsSuccessStatusCode){
                           string apiResponse = await response.Content.ReadAsStringAsync();
                           return JsonConvert.DeserializeObject<List<IncidentModel>>(apiResponse);
                          }
                           
                    }
                }
            }

You can add headers as well. Please verify your api end point link

CodePudding user response:

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

  • Related