准备使用uint路由约束吗?

问题描述 投票:0回答:1

我有一个.NET Core Web API项目,我的ID是从1开始的整数。在大多数示例中,我看到这样的东西

[HttpGet("{id:int}")]
public async Task<ActionResult<User>> GetUserByIdAsync([FromRoute] int id)
{
    // ...
}

因为我知道Ids必须大于0,所以我还添加了:min(1)路由约束。但是将整数数据类型更改为uint会更好吗?该路线将是

"{id:uint:min(1)}"

并且方法参数将更改为

[FromRoute] uint id

但是很遗憾,uint约束不存在。我认为当不使用GUID来标识时,这是一个标准问题,因为数据库将从1开始自动生成整数ID。我试图创建自己的路由约束:

Startup文件中,我在ConfigureServices之后将其添加到services.AddControllers()方法中>

services.Configure<RouteOptions>(routeOptions =>   
{  
    routeOptions.ConstraintMap.Add("uint", typeof(UIntRouteConstraint));  
});

并且路线约束本身很简单

public class UIntRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (httpContext == null)
            throw new ArgumentNullException(nameof(httpContext));

        if (route == null)
            throw new ArgumentNullException(nameof(route));

        if (routeKey == null)
            throw new ArgumentNullException(nameof(routeKey));

        if (values == null)
            throw new ArgumentNullException(nameof(values));

        if (values.TryGetValue(routeKey, out object routeValue))
        {
            // check if param is a uint
            return UInt32.TryParse(routeValue.ToString(), out uint number);
        }

        return false;
    }
}

这似乎通过按id url调用get用户来进行测试时按预期工作。但是我不确定这个约束是否可以证明是子弹头,是否我以前需要过这些空检查。

是否存在准备使用的uint路由约束?我想我不是唯一需要这个的人。

我有一个.NET Core Web API项目,我的ID是从1开始的整数。在大多数示例中,我看到类似以下内容:[HttpGet(“ {id:int}”)]公共异步任务> ...] >

c# .net-core asp.net-core-webapi asp.net-routing
1个回答
0
投票

ASP.NET Core Constraints文件夹提供了创建约束的良好示例

© www.soinside.com 2019 - 2024. All rights reserved.