Rest HttpGetAttribute不';不能在核心web api中工作

Rest HttpGetAttribute不';不能在核心web api中工作,rest,.net-core,routing,http-get,webapi,Rest,.net Core,Routing,Http Get,Webapi,众所周知的情况。我需要两个端点 GetAll->api/品牌 GetById->api/brands/1 [ApiController] [Route("api/[controller]")] public class BrandsController : ControllerBase { private readonly BrandRepository repository; public BrandsController(BrandRepository repository

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

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);
    }}
为了

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();
        }
    }
}
命名空间后台
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
services.AddDbContext(
选项=>
options.UseMySql(Configuration.GetConnectionString(“local”));
services.AddTransient();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(
端点=>
{
endpoints.MapControllers();
});
app.UseCors();
}
}
}
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

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

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

对于GetById操作:

[HttpGet(“{id}”)]
公共异步任务GetById(int id)
{
var brand=await repository.FindAsync(id);
如果(品牌==null)
{
返回NotFound();
}
返回Ok(品牌);
}
对于GetAll操作:

[HttpGet]
public IActionResult GetAll()
{
var brands=repository.GetAll().ToList();
返回Ok(品牌);
}
这将告诉路由中间件要调用哪个操作。对于要映射到基本控制器路由(即“api/brands”)的操作,只需使用不带重载的属性。例如[HttpGet]、[HttpPost]、[HttpDelete]。对于具有路由参数的操作,可以使用[HttpGet(“{id}”)]等等,具体取决于HTTP方法。不用担心在属性路由模板中定义参数的类型。在动作的参数中定义参数。例如:

[HttpGet(“{id}”)]
公共异步任务GetById(int id)
{
//代码在这里
返回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.MapControllers();
});

确保app.UseRouting()已启动;在app.UseEndpoints()之前调用

从那里开始[Route(“api/brand/[controller]”),然后您就可以使用自己的代码了fine@JahongirSabirov这将导致路线被映射为“api/品牌/品牌”。控制器路由模板很好,问题在于控制器操作本身的路由映射。嗨,@jandew!谢谢,我试着做了你提到的所有更改,但没有帮助。你的评论看起来不错,它适合所有关于WebAPI路由的信息,但对我来说不适用。可能Startup.cs文件错误或最新的.net core版本被破坏(看起来您在postman中使用了查询参数。您提供的屏幕截图将向“api/brands?id=2”发送请求。您需要向“api/brands/2”发送请求“。ID是一个路由参数,不是查询参数。我希望清除它。你是最好的中最好的!非常感谢。这很有帮助。我很久没有使用api路由,忘记了路由参数)))通常用于查询或正文:)
[HttpGet]
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();
        }
    }
}