angular - 将自定义 api 端点添加到 ASP :Net Core template

标签 angular asp.net-core asp.net-core-webapi

我尝试为 http 请求添加自己的端点。 我复制了天气预报中的逻辑,该逻辑是 asp.net core Angular 模板的一部分,并对其进行了修改:

原始Controlelr代码:

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;

    namespace AngularDemo.Controllers
    {
        [ApiController]
        [Route("[controller]")]
        public class WeatherForecastController : ControllerBase
        {
            private static readonly string[] Summaries = new[]
            {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
            };

            private readonly ILogger<WeatherForecastController> _logger;

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

            [HttpGet]
            public IEnumerable<WeatherForecast> Get()
            {
                var rng = new Random();
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }
        }
    }

这是我的测试 Controller

   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;

    namespace AngularDemo.Controllers
    {
        [ApiController]
        [Route("[controller]")]
        public class TestController: ControllerBase
        {

            private readonly ILogger<WeatherForecastController> _logger;

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

            [HttpGet]
            public IEnumerable<string> Get()
            {

                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = 100,
                    Summary = "Test"
                })
                .ToArray();
            }
        }
    }

但我现在的问题是,如何从我的 Angular 应用程序中调用它? 这是我的 Angular 组件,它以“天气预报”作为参数。我应该在另一个组件中哪里配置它,该组件应该向 TestController 发出请求?

Angular 天气组件:

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
  public forecasts: WeatherForecast[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'weatherforecast').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }
}

interface WeatherForecast {
  date: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

最佳答案

您的 Controller 由 [Route("[controller]")] 装饰。这意味着路由将设置为等于 Controller 类的名称减去后缀“Controller”。

在您的情况下:TestController相当于[Route("test")]

然后,您可以更改 Controller 类的名称或对 [Route] 属性的参数进行硬编码。

关于angular - 将自定义 api 端点添加到 ASP :Net Core template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60509064/

相关文章:

openid - AspNet.Security.OpenIdConnect.Server token 撤销和注销不起作用

angular - 如何使用 Bootstrap 4 不使用 JQuery 在 Angular 应用程序中实现自动完成输入字段

c# - 选择 webApi 模板时如何将 ASP.Net 身份添加到 Asp.Net Core?

c# - 处理 json 写入文件的 WebAPI Controller

asp.net-core - VS2019 : adding or renaming file in asp.net core 项目非常慢

azure - Stackexchange Redis异常: an unknown error occurred when writing the message

Angular 2 管道,正确使用 observable,我的管道不返回海报路径

javascript - angular2 xhrfields withcredentials true

Angular 4 Material Sidenav在被选中后不会关闭菜单

c# - Visual Studio Code launchurl 不适用于 Web API