Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于筛选响应的RESTURI参数_C#_Asp.net_Asp.net Mvc_Rest - Fatal编程技术网

C# 用于筛选响应的RESTURI参数

C# 用于筛选响应的RESTURI参数,c#,asp.net,asp.net-mvc,rest,C#,Asp.net,Asp.net Mvc,Rest,我试图根据从RESTURI检索的参数筛选从数据库检索的对象列表。示例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>

我试图根据从RESTURI检索的参数筛选从数据库检索的对象列表。示例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
EmployeeParametes.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)));
        }
    }
}
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()
    {
    }
}
    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"
            );
        }
Persistence.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)));
        }
    }
}
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()
    {
    }
}
    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"
            );
        }
公共列表GetEmployeeList() { string sqlString=“选择*来自员工”; MySqlCommand cmd=新的MySqlCommand(sqlString,conn); 列出员工=新列表(); 使用(MySqlDataReader=cmd.ExecuteReader()) { while(reader.Read()) { 添加(ReadFromDatabase(reader)); } } 返回员工; } 员工ReadFromDatabase(MySqlDataReader) { 如果(!dataReader.Read()) { 返回null; } 字符串firstName=null; 字符串lastName=null; 字符串出生地=null; 字符串currentPlace=null; int性别=-1; 字符串departmentCode=null; 字符串OIB=null; 尝试 { firstName=dataReader.GetString(1); lastName=dataReader.GetString(2); 出生地=dataReader.GetString(3); currentPlace=dataReader.GetString(4); 性别=dataReader.GetInt32(5); departmentCode=dataReader.GetString(6); OIB=dataReader.GetString(7); } 捕获(SqlNullValueException) { //记录错误 } 返回新员工( firstName!=null?firstName:“不适用”, lastName!=null?lastName:“不适用”, 出生地!=空?出生地:“不适用”, currentPlace!=null?currentPlace:“不适用”, 性别!=-1?(性别==1?EmployeeGender.M:EmployeeGender.F): EmployeeGender.UNDEFINED, 部门代码!=空? DepartmentCodeExtensions.GetEnumValue(DepartmentCode.NONE,DepartmentCode): 部门代码。无, OIB!=空?OIB:“不适用” ); }
我猜问题出在路线上,但不确定到底是什么或如何解决。非常感谢您的帮助。

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

正如您现在的代码一样,在从读卡器提取数据之前,将在读卡器中执行两次调用
.Read()

另一个问题是,如果读者无法阅读更多内容,您将
null
放入员工列表中,从而保证在尝试使用此元素的
FirstName
属性时出现
NullPointerException

请提供异常的完整堆栈跟踪,与三个.cs文件的完整内容一起-否则,很难判断错误在哪里。@J.N.已按要求更新。您是否已运行调试器并验证是Parameters对象为null,而不是Persistence类返回的
Employees
集合?