user19613128
user19613128

Reputation: 105

count records in web api?

i want to ask how to get total count with data in web api. i have tried use if clause to count total record, but it only shows the total count and the data didn't show in xml format.

Are there anyway to do without If clause?

example from json format:

{
  Count: 2
   [
    {
     "userid": 1,
     "name": "emily",
     "mobile": "98724954",
     "Age": 24,
     "Date": 2020-10-04T21:05:00
     },
     "userid": 2,
     "name": "peter",
     "mobile": "42896592",
     "Age": 35,
     "Date": 2021-05-25T11:20:00
     }
    ]

How to make the count like the example in the xml format?

Questions: How to Count data or response and show data together with xml format in web api?

my code:


        [HttpGet]
        public IHttpActionResult Get()
        {
            List<TestClass> draft = new List<TestClass>();
            string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
            SqlConnection sqlconn = new SqlConnection(mainconn);
            string sqlquery = "SELECT UserID, Name, Mobile, Age, Date From tbluser";
            sqlconn.Open();
            SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
            SqlDataReader sdr = sqlcomm.ExecuteReader();
            while (sdr.Read())
                {
                    draft.Add(new TestClass()
                    {
                        UserId = sdr.GetString(0),
                        Name = sdr.GetString(1),
                        Mobile = sdr.GetString(2),
                        Age = sdr.GetInt32(3),
                        Date = sdr.GetDateTime(4)
                    });
                }
            return Ok(draft);
        }
        if(test.Count>0)
        {
             return Ok(test.Count());
        }
        else
        {
             return Ok("None");
        };

results:

<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">10</int>

class:

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; }
    }

UPDATE

    [HttpGet]
    public IHttpActionResult Get()
    {
        List<TestClass> draft = new List<TestClass>();
        string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(mainconn);
        string sqlquery = "SELECT UserID, Name, Mobile, Age, Date From tbluser";
        sqlconn.Open();
        SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
        SqlDataReader sdr = sqlcomm.ExecuteReader();
        while (sdr.Read())
            {
                draft.Add(new TestClass()
                {
                    UserId = sdr.GetString(0),
                    Name = sdr.GetString(1),
                    Mobile = sdr.GetString(2),
                    Age = sdr.GetInt32(3),
                    Date = sdr.GetDateTime(4)
                });
            }
        var apiResult = new ApiResult
        {
            Count = api.Length,
            Data = api
        };
        var result= Ok(apiResult);
    }

Upvotes: 0

Views: 1714

Answers (1)

Xerillio
Xerillio

Reputation: 5261

You haven't given an example of what you expect as output, so it's a little difficult to know exactly how you want the XML to look. Also note, that your (invalid) JSON example does not match your TestClass, so I've assumed your TestClass is correct.

First, add a wrapper class so you can serialize the Count to XML as well:

public class TestApiResult
{
    public int Count { get; set; }
    public List<TestClass> Data { get; set; }
}

Update your controller action to put your data into an instance of this class:

[HttpGet]
public IHttpActionResult Get()
{
    string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
    using var sqlconn = new SqlConnection(mainconn);
    string sqlquery = "SELECT UserID, Name, Mobile, Age, Date From tbluser";
    sqlconn.Open();
    using var sqlcomm = new SqlCommand(sqlquery, sqlconn);
    using var sdr = sqlcomm.ExecuteReader();

    var data = new List<TestClass>();
    while (sdr.Read())
    {
        data.Add(new TestClass()
        {
            UserId = sdr.GetString(0),
            Name = sdr.GetString(1),
            Mobile = sdr.GetString(2),
            Age = sdr.GetInt32(3),
            Date = sdr.GetDateTime(4)
        });
    }

    // The important bit:
    var apiResult = new ApiResult
    {
        Count = data.Count,
        Data = data
    };
    var result= Ok(apiResult);
}

This will as an example result in the following XML:

<?xml version="1.0" encoding="utf-8"?>
<TestApiResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Count>3</Count>
  <Data>
    <TestClass>
      <UserId>fooID</UserId>
      <Name>fooName</Name>
      <Mobile>fooMobile</Mobile>
      <Access>1</Access>
      <Date>2022-08-11T00:00:00+00:00</Date>
    </TestClass>
    <TestClass>
      <UserId>barID</UserId>
      <Name>barName</Name>
      <Mobile>barMobile</Mobile>
      <Access>2</Access>
      <Date>2022-08-12T00:00:00+00:00</Date>
    </TestClass>
    <TestClass>
      <UserId>bazID</UserId>
      <Name>bazName</Name>
      <Mobile>bazMobile</Mobile>
      <Access>3</Access>
      <Date>2022-08-13T00:00:00+00:00</Date>
    </TestClass>
  </Data>
</TestApiResult>

Note: I've added some using statements to your code. It's important to remember, so that application resources are properly disposed when you're not using the object anymore. See the documentation for using to get more information.

Check this fiddle for a test.

Upvotes: 1

Related Questions