HttpGetAttribute在核心网络API中不起作用

问题描述 投票:0回答:1

众所周知的情况。我需要两个端点

GetAll-> api /品牌

GetById-> api / brands / 1

[ApiController]
[Route("api/[controller]")]
public class BrandsController : ControllerBase
{
    private readonly BrandRepository repository;

    public BrandsController(BrandRepository repository)
    {
        this.repository = repository;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult> GetById(int id)
    {
        var brand = await repository.FindAsync(id);
        if (brand == null)
        {
            return NotFound();
        }

        return Ok(brand);
    }

    [HttpGet("")]
    public ActionResult<IEnumerable<Brand>> GetAll()
    {
        var brands = repository.GetAll().ToList(); 

        return Ok(brands);
    }}

所以,我总是进入GetAll()有任何想法吗?帮助,请:)

Postman request

这是正确的名称空间吗?

using Microsoft.AspNetCore.Mvc;

for

[HttpGet]

Startup.cs

namespace BackOffice
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDbContext<ApplicationDbContext>(
                options => 
                options.UseMySql(Configuration.GetConnectionString("local")));

            services.AddTransient<BrandRepository, BrandRepository>();
        }

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

            app.UseCors();
        }
    }
}

dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd]

rest .net-core routing http-get webapi
1个回答
0
投票
将您的GetAll操作上的属性更改为[HttpGet],然后将您的GetById操作上的属性更改为[HttpGet(“ {id}”))]。

如果需要,您可以使用id的约束,但是在您的情况下,我看不到任何需要。通常,当您在同一路径上有多个操作但参数类型不同时,可以使用约束。例如,通过整数ID获取“ api / brands / 1”,然后您可能还有另一个映射到“ api / brands / gucci”的操作,该操作将按字符串名称搜索品牌。然后,您可以在路由模板中使用{id:int}和{id:string}约束来定义要调用的操作。

还要在声明操作返回类型时确保使用IActionResult。您不想使用具体的ActionResult类型。下面的代码示例。

对于GetById操作:

[HttpGet("{id}")] public async Task<IActionResult> GetById(int id) { var brand = await repository.FindAsync(id); if (brand == null) { return NotFound(); } return Ok(brand); }

对于您的GetAll操作:

[HttpGet] public IActionResult<IEnumerable<Brand>> GetAll() { var brands = repository.GetAll().ToList(); return Ok(brands); }

这将告诉路由中间件要调用哪个动作。对于您想要映射到基本控制器路由的操作(即“ api / brands”),只需使用该属性即可,而不会导致过载。例如[HttpGet],[HttpPost],[HttpDelete]。对于具有route参数的操作,则可以根据HTTP方法使用[HttpGet(“ {id}”)]等。不必担心在属性路由模板中定义参数的类型。您可以在操作的参数中定义参数。例如:

[HttpGet("{id}")] public async Task<IActionResult> GetById(int id) { // Code here return Ok(); }

[如果您想将路线映射到诸如“ api / brands / designers / 2”之类的地址,则可以使用[HttpGet(“ designers / {id}”))之类的模板。不要在设计者之前加上“ /”。 

编辑:忘记提及,请确保已正确配置Startup.cs以进行Web API路由。您可以阅读ASP.NET Core 3.1文档上的所有不同选项的详细信息。如果您使用了Web API模板,则可能不错,但值得仔细检查,因为配置不正确的端点路由可能会引起问题。确保在Startup.cs的Configure方法中具有以下内容。

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

确保该app.UseRouting();在app.UseEndpoints();]前调用
© www.soinside.com 2019 - 2024. All rights reserved.