我正在制作一个 GET API,但我在 API 中定义的路线没有触发我尝试了所有方法,但它无法工作。查看我在其中添加的以下代码文件。
我已经设置了一个 GET API 端点来从数据库中获取数据,但尽管我付出了努力,它仍然没有触发。下面是相关的代码文件。我在尝试从数据库获取数据时遇到配置问题。
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;
}
}
}
}
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; }
}
}
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 }
);
}
}
}
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"));
}
}
}
我遇到的错误
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'[email protected]', 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'[email protected]', 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'[email protected]', 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'[email protected]', 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'[email protected]', N'Male', CAST(N'2022-11-12T00:00:00.000' AS DateTime))
SET IDENTITY_INSERT [dbo].[Employees] OFF
GO
**
我更改了路线设置,但它不起作用。请帮助我解决这个问题,以便我能理解为什么我面临这个问题。
我解决了这个错误,因为在 WebConfig.cs 文件中定义的路由我对代码做了一些更改,并在此处删除了一些汇编,这是此 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 }
);
}
}
}
通过执行此操作,API 会给出响应,现在可以正常工作了。