首页 > 解决方案 > 将 API 控制器添加到 ASP.NET Core 项目

问题描述

这是搭建和编辑的控制器。

namespace TheAspNetCoreProject
{
    [Route("api/TheApi")]
    [ApiController]
    public class TheApiController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetInfo()
        {
            return Ok("Foo");
        }
    }
}

我希望看到它/api/TheApi//api/TheApi/Info/api/TheApi/GetInfo但什么都没有。

脚手架没有做任何事情Startup.cs,但是例如在文档中没有提到需要任何东西Startup.cs——这听起来不太可能。

我怎样才能让它工作?

标签: c#asp.net-web-apiasp.net-core-webapi

解决方案


I've just fired up VS and did a new .net core Web Api project from template and it works as you would expect to work:

[ApiController]
[Route("api/TheApi")]
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();
    }
    [HttpGet("OtherGet")]
    public IEnumerable<WeatherForecast> OtherGet()
    {
        var rng = new Random();
        return Enumerable.Range(1, 2).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

Valid urls:

Startup.cs looks like this:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

UPDATE: Also keep in mind that you can not have multiple GET/POST etc methods in one controller, only if you use the annotation for the others (or for all of them) like I did with OtherGet: HttpGet("OtherGet")]. If you don't use this annotation and have multiple GET, POST etc methods you will have exception: AmbiguousMatchException: The request matched multiple endpoints.


推荐阅读