【问题标题】:URI parameter in ASP.NETASP.NET 中的 URI 参数
【发布时间】:2022-01-10 01:23:50
【问题描述】:

我正在尝试使用 API 从 SQL Server 数据库中获取数据,在该 API 中我将两个日期作为参数传递以过滤数据,但每次执行此操作时都会引发异常。

这是我的get函数:

public class ValuesController : ApiController
{
    SqlConnection con = new SqlConnection(@"server =PC-UXYTHBB; database=TEST; User ID=sa;Password=pwdpwd");

    // GET api/values 
    public String Get(string d1, string d2)
    {
        SqlDataAdapter da = new SqlDataAdapter("SELECT *  FROM [dbo].[EMPLOYEE] where [birthdate] BETWEEN  @d1 and @d2  ", con);

        DataTable dt = new DataTable();
        da.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            return JsonConvert.SerializeObject(dt);
        }
        else
        {
            return "No data found !!";
        }
}

这是路由配置

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                    routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

【问题讨论】:

  • 它抛出什么异常?将异常详细信息添加到帖子中。

标签: asp.net-mvc api parameter-passing


【解决方案1】:

您没有将参数发送到查询。 你应该写这样的代码

da = new SqlDataAdapter("SELECT *  FROM [dbo].[EMPLOYEE] where [birthdate] BETWEEN @d1 and @d2", con);
da.SelectCommand.Parameters.AddWithValue("@d1",Convert.ToDateTime(d1));
da.SelectCommand.Parameters.AddWithValue("@d2",Convert.ToDateTime(d2));

【讨论】:

    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多