我在寫一個簡單的RESTful控制器。到目前爲止,我可以通過調用http://127.0.0.1:8080/api/employee/5
來檢索Employee
類型的單個JSON對象。但是在致電http://127.0.0.1:8080/api/employee/
時,我無法檢索到Employee
對象的集合。這給我以下錯誤。REST地獲取JSON列表
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://127.0.0.1:8080/api/employee/'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'employee'.
</MessageDetail>
</Error>
當我嘗試保存新員工時,會發生同樣的事情。
EmployeeApiController.cs
[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController
{
readonly EmployeePersistence persistence;
public EmployeeApiController()
{
persistence = new EmployeePersistence();
}
[HttpPost]
public void Post([FromBody] Employee employee) // DOESN'T WORK
{
// saving id for the debugging purposes
long id = persistence.SaveEmployee(employee);
}
[HttpGet]
[Route("{id:long}")]
public IHttpActionResult GetEmployee(long id) // WORKS
{
return Ok(
new Employee("Bobby", "Smedley",
"London", "Teheran",
EmployeeGender.M,
DepartmentCode.D_21570,
"12345678901"));
}
[HttpGet]
public IHttpActionResult ListEmployees() // DOESN'T WORK
{
return Ok(
new List<Employee> {
new Employee("Bobby", "Smedley",
"London", "Teheran",
EmployeeGender.M,
DepartmentCode.D_21570,
"12345678901"),
new Employee("Robbie", "Medleigh",
"Liverpool", "Teheran",
EmployeeGender.M,
DepartmentCode.D_21570,
"12345678901")});
}
}
任何想法,爲什麼每個ID的作品得到的,卻得到了一個列表,產後不要在這裏工作?
UPDATE 添加Route
導致以下問題ListEmployees
以上:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'MyWebService.Models.Employee' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.InvalidDataContractException
</ExceptionType>
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
您能向我們展示路線表嗎?嘗試在ListEmployees上添加'[Route]' – Marusyk
嘗試在兩個不起作用的方法之上添加'[Route(「」)]''。 –