Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting System.InvalidOperationException: The constraint reference ' int' could not be resolved to a type

Everything has been working in the API for weeks and then today I made a change to add another controller method and now none of the routing works.

Controller def:

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

method def added:

    /// <summary>
    /// Get Members of Group
    /// </summary>
    /// <param name="groupId">Id of the group to retreive members from</param>
    /// <returns>The http status code 204 if sucessful</returns>
    [AllowAnonymous]
    [HttpGet("Members/{id:int}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public IActionResult Members(int id)
    {
        var members = _groupLib.GetMembers(id);
        if (members == null)
        {
            return NotFound();
        }

        return Ok(members);
    }

As you can see there is a constraint applied to id but that has been used by other methods within the controller.

I even tried removing the constraint but no joy. Methods that don't require a constraint have also stopped working.

Here is my startup.cs

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.AddCors();
        new ConfigDIServices(services);
        services.AddAutoMapper(typeof(ObjectMappings));
        services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();

        services.AddDbContext<AppIdentityContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<IdentityUser, IdentityRole>(options =>
        {
            options.Password.RequiredLength = 8;
            options.Password.RequireDigit = false;
            options.Password.RequireLowercase = false;
        }).AddEntityFrameworkStores<AppIdentityContext>();

        services.AddApiVersioning(options =>
        {
            options.AssumeDefaultVersionWhenUnspecified = true;
            options.DefaultApiVersion = new ApiVersion(1, 0);
            options.ReportApiVersions = true;
        });
        services.AddVersionedApiExplorer(options =>
        {
            options.GroupNameFormat = "'v'VVV";
        });
        services.AddSwaggerGen();

        // Get AppSettings
        var appsettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appsettingsSection);

        var appSettings = appsettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);

        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false

            };
        });

        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, IApiVersionDescriptionProvider provider)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseSwagger();
        // Swagger UI options
        app.UseSwaggerUI(options =>
        {
            foreach (var desc in provider.ApiVersionDescriptions)
            {
                options.SwaggerEndpoint($"/Swagger/{desc.GroupName}/swagger.json", desc.GroupName.ToUpperInvariant());
            }
            options.RoutePrefix = "";
            options.DocExpansion(DocExpansion.None);
        });

        app.UseRouting();
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
        );
        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
like image 334
MDC Avatar asked Oct 24 '25 13:10

MDC


1 Answers

This turned out to be that there was a space between the parameter and the constraint type and in another controller.

I had this

[HttpGet("GetGroupLeaders/{id: int}")] 

and when changed to

[HttpGet("GetGroupLeaders/{id:int}")]

Everything started working. I would consider this a "bug" with a workaround. The constraint should be trimmed before testing.

like image 169
MDC Avatar answered Oct 27 '25 01:10

MDC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!