You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Web API 2中如何在GetById接口添加正则表达式实现ID搜索?

在ASP.NET Web API 2的GetById接口中实现正则表达式ID搜索

当然可行,但你当前的代码存在两个核心问题:一是完全没有利用传入的id参数进行筛选,直接查询了整张表;二是int类型的ID无法直接做正则匹配。下面分两种方案给你修改思路:

方案一:数据库层面正则筛选(推荐,适合大数据量)

SQL Server 2017及以上版本(或Azure SQL)支持REGEXP_LIKE函数实现正则匹配,低版本可以用PATINDEX实现简单的模式匹配。同时必须用参数化查询避免SQL注入风险。

修改后的代码示例:

using System.Text.RegularExpressions;

public IHttpActionResult GetById(string idPattern)
{
    // 验证正则表达式语法是否合法
    try
    {
        _ = new Regex(idPattern);
    }
    catch (ArgumentException)
    {
        return BadRequest("无效的正则表达式格式");
    }

    List<TestClass> draft = new List<TestClass>();
    string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
    
    // SQL Server 2017+ 用REGEXP_LIKE实现正则匹配
    string sqlquery = @"Select UserID, Name, Mobile, Access, Date 
                        From tblTest 
                        Where REGEXP_LIKE(CAST(UserID AS VARCHAR(20)), @IdPattern)";

    using (SqlConnection sqlconn = new SqlConnection(mainconn))
    {
        sqlconn.Open();
        using (SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn))
        {
            sqlcomm.Parameters.AddWithValue("@IdPattern", idPattern);
            using (SqlDataReader sdr = sqlcomm.ExecuteReader())
            {
                while (sdr.Read())
                {
                    draft.Add(new TestClass()
                    {
                        UserId = Convert.ToInt32(sdr["UserID"]),
                        Name = sdr["Name"].ToString(),
                        Mobile = sdr["Mobile"].ToString(),
                        Access = Convert.ToInt32(sdr["Access"]),
                        Date = Convert.ToDateTime(sdr["Date"])
                    });
                }
            }
        }
    }

    return Ok(draft);
}

如果你的SQL Server版本低于2017,把SQL语句改成用PATINDEX(支持通配符模式,类似简化版正则):

string sqlquery = @"Select UserID, Name, Mobile, Access, Date 
                    From tblTest 
                    Where PATINDEX(@IdPattern, CAST(UserID AS VARCHAR(20))) > 0";

方案二:内存层面正则筛选(适合小数据量)

如果不想修改SQL或者数据库版本不支持正则函数,可以先查询全表数据,再用C#的Regex类在内存中筛选:

using System.Text.RegularExpressions;

public IHttpActionResult GetById(string idPattern)
{
    Regex regex;
    try
    {
        regex = new Regex(idPattern);
    }
    catch (ArgumentException)
    {
        return BadRequest("无效的正则表达式格式");
    }

    List<TestClass> draft = new List<TestClass>();
    string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
    string sqlquery = "Select UserID, Name, Mobile, Access, Date From tblTest";

    using (SqlConnection sqlconn = new SqlConnection(mainconn))
    {
        sqlconn.Open();
        using (SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn))
        {
            using (SqlDataReader sdr = sqlcomm.ExecuteReader())
            {
                while (sdr.Read())
                {
                    draft.Add(new TestClass()
                    {
                        UserId = Convert.ToInt32(sdr["UserID"]),
                        Name = sdr["Name"].ToString(),
                        Mobile = sdr["Mobile"].ToString(),
                        Access = Convert.ToInt32(sdr["Access"]),
                        Date = Convert.ToDateTime(sdr["Date"])
                    });
                }
            }
        }
    }

    // 用正则筛选符合条件的ID
    var filteredResult = draft.Where(t => regex.IsMatch(t.UserId.ToString())).ToList();
    return Ok(filteredResult);
}

注意事项

  • 接口参数从int id改为string idPattern,这样用户可以通过URL传入正则模式,比如GET /api/yourcontroller/GetById?idPattern=^123.*
  • 必须添加正则语法验证,避免非法正则导致程序崩溃
  • 优先选择数据库层面筛选,避免全表查询带来的性能问题
  • 始终使用using语句管理数据库连接、命令、阅读器,确保资源正确释放

内容的提问来源于stack exchange,提问作者user27429245

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:27:27