c# - 字符串路由约束

标签 c# routes asp.net-core-mvc asp.net-core-webapi asp.net-core-1.1

我有一个 ASP .Net Core 1.1 MVC Web API。如何在 Controller 操作中使用字符串路由约束?

我有以下两个 Action :

/ GET: api/Users/5
[HttpGet("{id:int}")]
[Authorize]
public async Task<IActionResult> GetUser([FromRoute] int id)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    User user = await _context.User.SingleOrDefaultAsync(m => m.UserId == id);

    if (user == null)
        return NotFound();

    return Ok(user);
}

// GET: api/Users/abcde12345
[HttpGet("{nameIdentifier:string}")]
[Authorize]
public async Task<IActionResult> GetUserByNameIdentifier([FromRoute] string nameIdentifier)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    User user = await _context.User.SingleOrDefaultAsync(m => m.NameIdentifier == nameIdentifier);

    if (user == null)
        return NotFound();

    return Ok(user);
}

第一个有效但第二个无效 - .Net 不喜欢“字符串”约束。所以基本上,我再次执行 HTTPGET 请求:

http://mywebsite.com/api/users/5

如果我要求,它必须执行第一个 Action

http://mywebsite.com/api/users/abcde

它必须执行第二个...有什么想法吗?谢谢...

最佳答案

如@Aistis 所述,路由数据默认为字符串。这就是没有路由约束将数据类型强制为字符串的原因。如果您想将值限制为特定的字符串值,您正在使用的字符串约束很有用,它不能用于将类型强制为字符串。有几个选项可以实现您想要做的事情。

1.使用正则表达式路由约束。请注意,您需要根据需要更改正则表达式。

// GET: api/Users/abcde12345
[HttpGet("{nameIdentifier:regex(^[[a-zA-Z]])}")]
[Authorize]
public async Task<IActionResult> GetUserByNameIdentifier([FromRoute] string nameIdentifier)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    User user = await _context.User.SingleOrDefaultAsync(m => m.NameIdentifier == nameIdentifier);

    if (user == null)
        return NotFound();

    return Ok(user);
}

2.您可以如下实现自己的路由约束,再次更改正则表达式以满足您的需要。

public class NameIdRouteConstraint : RegexRouteConstraint
{
    public NameIdRouteConstraint() : base(@"([A-Za-z]{3})([0-9]{3})$")
    {
    }
}

现在,您可以在 Startup.cs 中映射此自定义路由约束,如下所示

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.Configure<RouteOptions>(options =>
         options.ConstraintMap.Add("nameId", typeof(NameIdRouteConstraint )));
}

自定义路由约束“nameId”已准备好使用,如下所示

 // GET: api/Users/abcde12345
[HttpGet("{nameIdentifier:nameId}")]
[Authorize]
public async Task<IActionResult> GetUserByNameIdentifier([FromRoute] string nameIdentifier)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    User user = await _context.User.SingleOrDefaultAsync(m => m.NameIdentifier == nameIdentifier);

    if (user == null)
        return NotFound();

    return Ok(user);
}

关于c# - 字符串路由约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44694658/

相关文章:

c# - File.ReadLines().ToList() 在包含 2 个空行的文件上的计数为 1?

php - 如何在 Laravel 中做一个简单的重定向?

.net - 我可以使用 EF Code First 和 .net core 生成迁移脚本吗

c# - 存储库模式 EF Core 更新方法

c# - 单元测试失败后如何强制Visual Studio构建失败

javascript - 根据日期时间字段填充文本框。 ASP.NET C# JS

c# - 删除 "/*"和 "*/"之间的文本( block 注释)

ios - 通过 Google map 或 Apple map (iOS) 使用自定义路线

使用 Slug 的 C# Mvc 通用路由

asp.net-identity - 在 ASP.NET Core 中使用 Autofac 注册 UserManager