RESTful获取JSON列表

时间:2017-07-06 10:01:02

标签: c# asp.net asp.net-mvc rest

我正在编写一个简单的RESTful控制器。到目前为止,我可以通过调用Employee来检索http://127.0.0.1:8080/api/employee/5类型的单个JSON对象。但是在调用Employee时,我无法检索http://127.0.0.1:8080/api/employee/个对象的集合。这给我带来了以下错误。

<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都可以使用,但是获取一个列表,然后发布不在这里工作?

更新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 }
        );
    }
}

1 个答案:

答案 0 :(得分:1)

您可以在[Route]操作上添加属性ListEmployees或检查您的路线表

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