如何在ASP.NET Razor Web应用程序中调用ASP.NET API

发布于 2025-02-05 20:31:13 字数 1413 浏览 1 评论 0原文

我正在构建一个带有Mongo数据库的ASP.NET Core 6 Web应用程序和一个带有Mongo数据库的ASP.NET API。我有API,它返回JSON中的正确数据,但是我不知道如何在Web应用程序中调用此数据并在剃须刀页面上显示数据。这是我到目前为止的代码

无法分配请求的地址(Localhost:52189)

这是我在控制器类中的代码

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;
    }
}

,然后是剃须刀页面(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();
    }
}

,我如何正确调用此API并在index上显示数据.cshtml页面?任何帮助或教程链接将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纵性 2025-02-12 20:31:13

在Web应用程序中调用此数据,并在剃须刀页面上显示数据

,更改下面的代码,然后您可以在ASP.NET剃须刀中调用ASP.NET API并获取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);
        }

此外:下面是工作演示(显示)关于在剃须刀页面上显示数据的index.cshtml中的汽车列表,您可以参考它:

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>
}

结果:

”

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

不甘平庸 2025-02-12 20:31:13

您可以使用httpclient调用API终点,这是代码。

  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);
                          }
                           
                    }
                }
            }

您也可以添加标题。请验证您的API终点链接

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文