Uğur Canbulat
Uğur Canbulat

Reputation: 2296

The constraint reference 'string' could not be resolved to a type. (netcoreapp3.0)

I have got an error. This is my Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}

public void Configure(IApplicationBuilder app)
{
    app.UseDeveloperExceptionPage();

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

Current technology "netcoreapp3.0" and my controller is.

[Route("api/[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
    [HttpGet("request")]
    public ActionResult Index()
    {
        return Ok();
    }
}

And here is my error. I couldn't find a solution, I even didn't get what exactly this is. So here we are.

System.InvalidOperationException: The constraint reference 'string' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'.
   at Microsoft.AspNetCore.Routing.DefaultParameterPolicyFactory.Create(RoutePatternParameterPart parameter, String inlineText)
   at Microsoft.AspNetCore.Routing.ParameterPolicyFactory.Create(RoutePatternParameterPart parameter, RoutePatternParameterPolicyReference reference)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.CreateCandidate(Endpoint endpoint, Int32 score)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.CreateCandidates(IReadOnlyList`1 endpoints)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.AddNode(DfaNode node, DfaState[] states, Int32 exitDestination)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.AddNode(DfaNode node, DfaState[] states, Int32 exitDestination)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.<AddNode>g__Transition|19_0(DfaNode next, <>c__DisplayClass19_0& )
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.AddNode(DfaNode node, DfaState[] states, Int32 exitDestination)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.AddNode(DfaNode node, DfaState[] states, Int32 exitDestination)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.AddNode(DfaNode node, DfaState[] states, Int32 exitDestination)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.AddNode(DfaNode node, DfaState[] states, Int32 exitDestination)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.Build()
   at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher.CreateMatcher(IReadOnlyList`1 endpoints)
   at Microsoft.AspNetCore.Routing.DataSourceDependentCache`1.Initialize()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at System.Threading.LazyInitializer.EnsureInitialized[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher..ctor(EndpointDataSource dataSource, Lifetime lifetime, Func`1 matcherBuilderFactory)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherFactory.CreateMatcher(EndpointDataSource dataSource)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.InitializeCoreAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|8_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task`1 matcherTask)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

EDIT: There is my dependencies. When I remove these then it worked.

<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.0">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Caching.SqlServer" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.0.0-rc4" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0-rc4" />
<PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="3.0.24" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />

Upvotes: 64

Views: 69103

Answers (8)

Tim Yates
Tim Yates

Reputation: 1

.MapGet("{Id:guid}/string", async (Guid Id, Service service) =>...

I had a typo here where the bracket was misplaced to the end of the string

Upvotes: 0

Reza Taba
Reza Taba

Reputation: 1904

Ahh, my issue was variable naming mismatch.

Not Working

[HttpGet("{id}")]
public async Task<ActionResult<UserDto>> Get(string userId) {
    //some code
}

userId should change to id to match the {id}

Working

[HttpGet("{id}")]
public async Task<ActionResult<UserDto>> Get(string id) {
    //some code
}

Upvotes: 2

InvalidOperationException: The constraint reference 'Admin' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'.

This error happen because of the configuration of midleware "MapControllerRoute" in program.cs, some persons are not change the ":" by "=". You must replace : pattern: "{area:Admin}/{controller=Category}/{action=Index}/{id?}" by pattern: "{area=Admin}/{controller=Category}/{action=Index}/{id?}"

look at the part circled with red color

Upvotes: 0

Aaron
Aaron

Reputation: 1

This is not same:

[HttpGet("example/{param1:string}/{param2:Guid}")] 

as this:

[HttpGet("example/{param1: string}/{param2:Guid}")]

Check the space in the type after param1: in the second example.

If it recognizes a space, it will throw an error.

Upvotes: 0

Naod Agere
Naod Agere

Reputation: 59

In my case it was just a single space between the route parameter and the data type ({id: int})

Upvotes: 2

Raymond Coplin
Raymond Coplin

Reputation: 99

It could be a blank space between the param name and the type.

Example:

{param1 :alpha} 🚫

{param1:alpha} ✅

Upvotes: 6

Uğur Canbulat
Uğur Canbulat

Reputation: 2296

In case you use something like

[HttpGet("example/{param1:string}/{param2:Guid}")]

change it to

[HttpGet("example/{param1}/{param2:Guid}")]

because ":string" is actually interpreted as a regex-validation-constraint and not a type definition and guess what, everything is reaching the server as string and there is no string-regex-validator :)

Upvotes: 152

paultechguy
paultechguy

Reputation: 2518

I also encountered this recently. The fix for me as to use "alpha" as a replacement for the string type:

[HttpGet("example/{param1:alpha}")]

This was documented in the Microsoft documentation.

Upvotes: 21

Related Questions