I want to ask how to pass datetime parameter in Web API, how to pass datetime parameter in optional date. I want to search in the URL can be optional date without time such as:
localhost:IP/api/values?date=2020-01-01
Expected results:
<ArrayOfTest xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Test>
<UserId>341</UserId>
<Name>Emily</Name>
<Mobile>386754298</Mobile>
<Age>24</Age>
<Date>2021-11-06T16:04:00</Date>
</Test>
<Test>
<UserId>2555</UserId>
<Name>Peter</Name>
<Mobile>48295729</Mobile>
<Age>45</Age>
<Date>2020-10-12T20:35:00</Date>
</Test>
It can found out date after 2020-01-01. some value are null from SQL Server database, so I used dbnull to make sure the code works and I didn't use Entity Framework to connect the database, I have try to just pass datetime parameter in get method and it is not work as well. Is it possible to pass datatime parameter like this way?
Class code:
public class TestClass
{
public string UserId { get; set; }
public string Name { get; set; }
public string Mobile { get; set; }
public int Age { get; set; }
public DateTime? Date { get; set; }
}
controller code:
public IHttpActionResult Get(DateTime date)
{
List<UserClass> Test = new List<UserClass>();
string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "SELECT UserID, Name, Mobile, Age, Date From tbluser where Date="+date;
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
SqlDataReader reader = sqlcomm.ExecuteReader();
while (reader.Read())
{
Test.Add(new UserClass()
{
UserId = reader.GetValue.ToString(0),
Name = reader.GetValue.ToString(1),
Mobile = reader.GetValue.ToString(2),
Access = Convert.ToInt32(reader.GetValue(3)),
Date = Convert.ToDateTime(reader.GetValue(4))
});
}
return Ok(Test);
}