Search code examples
c#asp.netruntime-error

API Response issue


i am making a GET API but the route which i defined in API is not triggering i try every thing but it cannot work. look into the below codes files i added in it.

I've set up a GET API endpoint to fetch data from a database, but it's not triggering despite my efforts. Below are the relevant code files. I'm encountering configuration issues while attempting to fetch data from the database.

The API Controller File
using API_develop.Models;
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Configuration;
using System.Web;
using System.Web.Mvc;

namespace API_develop.Controllers
{
    public class APIController : Controller
    {

        string congemp =        ConfigurationManager.ConnectionStrings["Empconectionstring"].ConnectionString;
        // GET: API
        [HttpGet]
        [Route("API/emodata")]
        public IList<EMPdatalist> EMPdatalist()
        { 
            IList<EMPdatalist> getdata = new List<EMPdatalist>();
            {
                using (SqlConnection conn = new SqlConnection(congemp))
                {
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "SELECT id, firstname, lastname, email FROM Employees";

                        SqlDataAdapter da = new SqlDataAdapter(cmd); // Associate SqlCommand with   SqlDataAdapter
                        DataTable dt = new DataTable();
                        conn.Open();
                        da.Fill(dt);

                        try
                        {
                            if (dt != null)
                            {
                                foreach (DataRow row in dt.Rows)
                                {
                                    EMPdatalist emp = new EMPdatalist();
                                    emp.Id = Convert.ToInt32(row["id"].ToString());
                                    emp.FirstName = row["firstname"].ToString();
                                    emp.LastName = row["lastname"].ToString();
                                    emp.Email = row["email"].ToString();
                                    getdata.Add(emp);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            // Handle the exception (e.g., log it)
                            Console.WriteLine(ex.Message);
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }
                }
                return getdata;
            }
        }
    }
}
API Model Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace API_develop.Models
{
    public class EMPdatalist
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Gender { get; set; }
    }
}
Route Confiq.cs
using System.Web.Mvc;
using System.Web.Routing;

namespace API_develop
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
WebAPIConfig.cs File
using System;
using System.Web.Http;

namespace API_develop
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
                .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",
                                     "text/html",
                                     StringComparison.InvariantCultureIgnoreCase,
                                     true,
                                     "application/json"));
        }
    }
}

The error i am getting api/API/emodata

API/emodata

Database Script to get the data
USE [TokenAuthDB]
GO
/****** Object:  Table [dbo].[Employees]    Script Date: 7/5/2024 11:36:19 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Employees](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [nvarchar](max) NULL,
    [LastName] [nvarchar](max) NULL,
    [Email] [nvarchar](max) NULL,
    [Gender] [nvarchar](max) NULL,
    [CreatedDate] [datetime] NOT NULL,
 CONSTRAINT [PK_dbo.Employees] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Employees] ON 

INSERT [dbo].[Employees] ([Id], [FirstName], [LastName], [Email], [Gender], [CreatedDate]) VALUES (1, N'Benjamin', N'Jones', N'timothydavis@jennings.com', N'Male', CAST(N'2023-06-28T00:00:00.000' AS DateTime))
INSERT [dbo].[Employees] ([Id], [FirstName], [LastName], [Email], [Gender], [CreatedDate]) VALUES (2, N'David', N'Welch', N'lnelson@maldonado.net', N'Female', CAST(N'2020-04-07T00:00:00.000' AS DateTime))
INSERT [dbo].[Employees] ([Id], [FirstName], [LastName], [Email], [Gender], [CreatedDate]) VALUES (3, N'Jason', N'Young', N'powellrebecca@hotmail.com', N'Male', CAST(N'2019-06-19T00:00:00.000' AS DateTime))
INSERT [dbo].[Employees] ([Id], [FirstName], [LastName], [Email], [Gender], [CreatedDate]) VALUES (4, N'Brandon', N'Oneill', N'caseykennedy@yahoo.com', N'Male', CAST(N'2021-07-21T00:00:00.000' AS DateTime))

GO
INSERT [dbo].[Employees] ([Id], [FirstName], [LastName], [Email], [Gender], [CreatedDate]) VALUES (100, N'Mark', N'Figueroa', N'timothy02@gmail.com', N'Male', CAST(N'2022-11-12T00:00:00.000' AS DateTime))
SET IDENTITY_INSERT [dbo].[Employees] OFF
GO
**

I change the route setting but it cannot work. please help me to solve this problem so i can understand why i am facing this issue.


Solution

  • I solve this error this happen because the route which is defined in WebAPIConfig.cs file i make changes in code a little bit and removing some assembles here is the updated code for this API.

    **APIController.cs**
    
    using API_develop.Models;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.Http;
    
    namespace API_develop.Controllers
    {
        public class APIController : ApiController
        {
            string congemp = ConfigurationManager.ConnectionStrings["Empconectionstring"].ConnectionString;
    
            [HttpGet]
            [Route("api/API/emodata")]
            public IList<EMPdatalist> GetEMPdatalist()
            {
                IList<EMPdatalist> getdata = new List<EMPdatalist>();
                using (SqlConnection conn = new SqlConnection(congemp))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;;
                        cmd.CommandText = "SELECT id, firstname, lastname, email FROM Employees";
    
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        DataTable dt = new DataTable();
                        conn.Open();
                        da.Fill(dt);
    
                        try
                        {
                            if (dt != null)
                            {
                                foreach (DataRow row in dt.Rows)
                                {
                                    EMPdatalist emp = new EMPdatalist
                                    {
                                        Id = Convert.ToInt32(row["id"].ToString()),
                                        FirstName = row["firstname"].ToString(),
                                        LastName = row["lastname"].ToString(),
                                        Email = row["email"].ToString()
                                    };
                                    getdata.Add(emp);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            // Handle the exception (e.g., log it)
                            Console.WriteLine(ex.Message);
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }
                }
                return getdata;
            }
    
    }
    

    }

    **WebAPIConfig.cs**
    
    using System;
    using System.Web.Http;
    
    namespace API_develop
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
               
            }
        }
    }
    

    by doing this the API is giving response and now its working.