用于过滤响应的REST URI参数

时间:2017-07-08 10:36:55

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

我正在尝试根据从REST URI检索的参数过滤从数据库中检索的对象列表。示例URI将是http://127.0.0.1:8080/api/employee?FirstName=Abigail&LastName=Ybarra,它将检索具有指定名字和姓氏的对象列表。

我在点击这样的URI时遇到的错误如下:

<ExceptionMessage>
Object reference not set to an instance of an object
</ExceptionMessage>
<ExceptionType>System.NullReferenceException</ExceptionType>

MyWebService.Controllers.EmployeeApiController+<>c__DisplayClass4_0.<ListEmployees>b__0 (MyWebService.Models.Employee x) [0x00000] in <8bf6371a770245f989f67352a05d8bb6>:0 at System.Linq.Enumerable+WhereListIterator`1[TSource].MoveNext () [0x00037] in /private/tmp/source-mono-2017-02/bockbuild-2017-02/profiles/mono-mac-xamarin/build-root/mono-x86/external/corefx/src/System.Linq/src/System/Linq/Where.cs:369 at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList

同样的事情发生在ie。 URI http://127.0.0.1:8080/api/employee?id=3,虽然它可以按预期用于URI http://127.0.0.1:8080/api/employee/3。它也可以按预期工作(从数据库中检索所有对象)以获取URI http://127.0.0.1:8080/api/employee/

唯一不起作用的是参数。这是代码。

Controller.cs

    [RoutePrefix("api/employee")]
    public class EmployeeApiController : ApiController
    {

        readonly EmployeePersistence persistence;


        public EmployeeApiController()
        {
            persistence = new EmployeePersistence();
        }

        [HttpGet]
        [Route("{id:long}")]
        public IHttpActionResult GetEmployee(long id) 
        {
            return Json(persistence.GetEmployee(id));
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult ListEmployees([FromUri] EmployeeParameters parameters)
        {
            return Json(persistence.GetEmployeeList().Where(x => x.FirstName.Equals(parameters.FirstName)));
        }
    }
}

EmployeeParametes.cs

public class EmployeeParameters
{
    /**
     * First name of the employee.
     */
    public string FirstName { get; set; }

    /*
     * Last name of the employee.
     */
    public string LastName { get; set; }

    /**
     * Place of birth of the employee.
     */
    public string BirthPlace { get; set; }

    /**
     * Gender of the employee.
     */
    public int Gender { get; set; }

    /**
     * OIB of the employee.
     */
    public string OIB { get; set; }


    /**
     *  Current place of the employee.
     */
    public string CurrentPlace { get; set; }


    /**
     *  Department code of the employee.
     */
    public string Department { get; set; }

    public EmployeeParameters()
    {
    }
}

Persistence.cs

    public List<Employee> GetEmployeeList()
        {
            string sqlString = "SELECT * FROM Employee";

            MySqlCommand cmd = new MySqlCommand(sqlString, conn);

            List<Employee> employees = new List<Employee>();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    employees.Add(ReadFromDatabase(reader));
                }
            }

            return employees;
        }

Employee ReadFromDatabase(MySqlDataReader dataReader)
        {
            if (!dataReader.Read())
            {
                return null;
            }

            string firstName = null;
            string lastName = null;
            string birthPlace = null;
            string currentPlace = null;
            int gender = -1;
            string departmentCode = null;
            string OIB = null;

            try
            {
                firstName = dataReader.GetString(1);
                lastName = dataReader.GetString(2);
                birthPlace = dataReader.GetString(3);
                currentPlace = dataReader.GetString(4);
                gender = dataReader.GetInt32(5);
                departmentCode = dataReader.GetString(6);
                OIB = dataReader.GetString(7);
            }
            catch (SqlNullValueException)
            {
                // log the error
            }

            return new Employee(
                firstName != null ? firstName : "N/A",
                lastName != null ? lastName : "N/A",
                birthPlace != null ? birthPlace : "N/A",
                currentPlace != null ? currentPlace : "N/A",
                gender != -1 ? (gender == 1 ? EmployeeGender.M : EmployeeGender.F) : 
                    EmployeeGender.UNDEFINED,
                departmentCode != null ?
                    DepartmentCodeExtensions.GetEnumValue(DepartmentCode.NONE, departmentCode) :
                    DepartmentCode.NONE,
                OIB != null ? OIB : "N/A"
            );
        }

我猜这个问题与路线有关,但不确定究竟是什么或如何解决它。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

我认为出现异常是因为在.Read() - 循环和方法while内调用了ReadFromDatabase。您应该删除后者的.Read()来电。

正如您的代码现在一样,在您从阅读器中提取数据之前,会在阅读器中执行两次.Read()调用。 另一个问题是,如果读者无法阅读更多内容,则会将null放入您的员工列表中,并在尝试使用NullPointerException属性时保证FirstName这个元素。