Adding a custom api endpoint to the ASP:Net Core template

Viewed 435

I try to add an own endpoint for a http request. I copied the logic from the weather forecast which is part of the asp.net core angular template and modified it:

Original Controlelr code:

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

And this is my TestController

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

But my question is now, how do I call it from my angular application? This is my component in angular which has "weatherforecast" as a parameter. Where do I configure it in another component, which should make a request to the TestController?

Angular weather component:

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

Your controller is decorated with [Route("[controller]")]. It means that the route will be set equal to the name of your controller class minus the suffix "Controller".

In your case: TestController is equivalent to [Route("test")].

You can then either change the name of your controller class or hard-code the argument of the [Route] attribute.

Related