在带有Api版本控制的Asp.Ner Core 3.1中,CreatedAtAction返回“没有路由与提供的值匹配” 500错误

时间:2020-07-20 11:37:17

标签: asp.net-core-webapi asp.net-core-3.1

我在带有Api版本控制的Asp.Net Core 3.1中有一个Web API项目,其设置如下:

[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
public abstract class BaseApiController : ControllerBase
{
    ...
}
我正在测试的

控制器:

public class RegistrationController : BaseApiController
{
    [HttpGet]
    [Route("{id}")]
    public async Task<ActionResult<RegistrationDTO>> GetRegistration(int id)
    {
        ...
    }

    [HttpPost]
    public async Task<IActionResult> Create(RegistrationCreateDTO item, ApiVersion apiVersion)
    {
        ...
        return CreatedAtAction(nameof(GetRegistration), new { id = itemId, version = $"{apiVersion.MajorVersion.Value}" }, itemId);
    }
}

由于某种原因,除非我删除[Route {“ id”}]并将[HttpGet]更改为[HttpGet {“ id”}],否则这是行不通的。知道是什么原因导致了这种行为吗?

请注意,我没有设置任何特定的路由,只是一个简单的app.UseHttpsRedirection();app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

1 个答案:

答案 0 :(得分:1)

这是一个演示作品: Startup.cs:

def gen_password():
    letters = string.ascii_letters
    random_letter = random.choice(letters)
    random_num = random.randint(0,9)
    letter_or_num = ["letter","number"]
    char_num = int(input("How many characters do you want in your password?: "))
   
    password = []
    for i in range(char_num):
        random_var = random.choice(letter_or_num)
        if random_var == "letter":
            random_letter = random.choice(letters)
            # replace print with this:
            password.append(random_letter)  
         
        elif random_var == "number":
            random_num = random.randint(0,9)
            password.append(str(random_num))
    return "".join(password)

print(gen_password())

BaseApiController:

public void ConfigureServices(IServiceCollection services)
        {

            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });
        }


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }

RegistrationController:

[ApiController]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class BaseApiController : ControllerBase
    {
        
    }

结果: enter image description here