我的一个Web API方法完美无缺,另一个根本没有。
完美地运作,我的意思是:
但是,另一个人似乎甚至都不了解自己。它通过以下方式回答浏览器请求:
这两个代码的代码似乎都是相同的,所以我不知道为什么一个代码就像魅力一样,而另一个代码却很失败。
相关代码是:
CONTROLLER
public class DepartmentsController : ApiController
{
private readonly IDepartmentRepository _deptsRepository;
public DepartmentsController(IDepartmentRepository deptsRepository)
{
if (deptsRepository == null)
{
throw new ArgumentNullException("deptsRepository is null");
}
_deptsRepository = deptsRepository;
}
[Route("api/Departments/Count")]
public int GetCountOfDepartmentRecords()
{
return _deptsRepository.Get();
}
[Route("api/Departments")]
public IEnumerable<Department> GetBatchOfDepartmentsByStartingID(int ID, int CountToFetch)
{
return _deptsRepository.Get(ID, CountToFetch);
}
REPOSITORY
public class DepartmentRepository : IDepartmentRepository
{
private readonly List<Department> departments = new List<Department>();
public DepartmentRepository()
{
using (var conn = new OleDbConnection(
@"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Freebo;Password=RunningOnEmpty;Data Source=C:\CDBWin\DATA\CCRDAT42.MDB;Jet OLEDB:System database=C:\CDBWin\Data\nrbq.mdw"))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT td_department_accounts.dept_no, IIF(ISNULL(t_accounts.name),'No Name provided',t_accounts.name) AS name FROM t_accounts INNER JOIN td_department_accounts ON t_accounts.account_no = td_department_accounts.account_no ORDER BY td_department_accounts.dept_no";
cmd.CommandType = CommandType.Text;
conn.Open();
int i = 1;
using (OleDbDataReader oleDbD8aReader = cmd.ExecuteReader())
{
while (oleDbD8aReader != null && oleDbD8aReader.Read())
{
int deptNum = oleDbD8aReader.GetInt16(0);
string deptName = oleDbD8aReader.GetString(1);
Add(new Department { Id = i, AccountId = deptNum, Name = deptName });
i++;
}
}
}
}
}
public int Get()
{
return departments.Count;
}
private Department Get(int ID) // called by Delete()
{
return departments.First(d => d.Id == ID);
}
如果输入:
http://shannon2:28642/api/Departments/Count
浏览器中的用于执行Controller的GetCountOfDepartmentRecords()方法,为什么输入:
http://localhost:28642/api/Departments/5/6
(或
http://localhost:28642/api/Departments/1/5
etc)无法执行Controller的GetBatchOfDepartmentsByStartingID()方法?
答案 0 :(得分:2)
您的路线缺少参数。
[Route("api/Departments/{ID:int}/{CountToFetch:int}")]
答案 1 :(得分:1)
此问题与您在下面的其他问题类似:
如果您希望值来自URL的非查询字符串部分,则需要在路径模板中定义它们。所以,它应该是
[Route("api/Departments/{id}/{countToFetch}")]
以下是关于Web API中的路由和操作选择的好文章:
http://www.asp.net/web-api/overview/web-api-routing-and-actions