【问题标题】:HttpGetAttribute doesn't work in core web apiHttpGetAttribute 在核心 Web api 中不起作用
【发布时间】:2020-03-14 12:45:21
【问题描述】:

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

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() 有任何想法吗?请帮忙:)

它是一个正确的命名空间吗?

using Microsoft.AspNetCore.Mvc;

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

dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

【问题讨论】:

  • 从那里制作 [Route("api/brand/[controller]")] 然后你可以使用你自己的代码它应该可以正常工作
  • @JahongirSabirov 这将导致路线被映射为“api/brand/brands”。控制器路由模板很好,问题在于控制器操作本身的路由映射。

标签: rest .net-core routing http-get webapi


【解决方案1】:

将 GetAll 操作的属性更改为 [HttpGet],然后将 GetById 操作的属性更改为 [HttpGet("{id}")] 。

如果需要,您可以使用约束来标识,但在您的情况下,我认为不需要它。通常,当您在同一条路线上有多个操作但具有不同的参数类型时,您可以使用约束。例如,“api/brands/1”通过整数 ID 获取,然后您可能有另一个映射到“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]。对于具有路由参数的操作,您可以使用 [HttpGet("{id}")] 等,具体取决于 HTTP 方法。不用担心在属性路由模板中定义参数的类型。您在操作的参数中定义参数。例如:

[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(); 之前调用;

【讨论】:

  • 嗨,@jandrew!谢谢,我尝试进行您提到的所有更改,但没有帮助。您的评论看起来不错,它适合有关 web api 路由的所有信息,但它对我不起作用。可能 Startup.cs 文件错误或最新的 .net 核心版本被破坏(
  • 您似乎在邮递员中使用查询参数。您提供的屏幕截图将向“api/brands?id=2”发送请求。您需要向“api/brands/2”发送请求。ID 是路由参数,而不是查询参数。我希望清除它向上
  • 你是最好的中最好的!非常感谢。它有帮助。我很长时间不使用 api 路由并且忘记了路由参数)))通常与查询或正文一起使用:)
猜你喜欢
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多