【问题标题】:Put method in web api (EF)将方法放入 web api (EF)
【发布时间】:2021-06-02 00:10:19
【问题描述】:

我正在使用 web api put 方法。我需要更新数据库中的两列。但我在更新这两列时遇到了问题。

我有一个错误如下所述

System.NullReferenceException: '对象引用未设置为 对象的实例。'

emp 为空。

这是我当前的代码;

public class EmployeeController : ApiController
{
    public HttpResponseMessage Put(int id, [FromBody] Employee emp)
    {
        try
        {
            using (EmpDBContext dbContext = new EmpDBContext())
            {
                var entity = dbContext.Employees.FirstOrDefault(e => e.Index == id);
                if (entity != null)
                {
                    entity.Name = emp.Name;
                    entity.EmpNum = emp.EmpNum;
                    dbContext.SaveChanges();

                    return Request.CreateResponse(HttpStatusCode.OK, entity);
                }
                else
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                        "Employee with Id " + id.ToString() + " not found to update");
                }
            }
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }


    }
}

需要一些关于这个问题的建议。

【问题讨论】:

  • 您的 PUT 请求是什么样的?
  • @Jasen, ,我想将姓名和员工编号更新到数据库中。姓名和员工编号将从其他用户开发的另一个 API 中获取。
  • 你需要弄清楚为什么emp(发送给API的模型)是null

标签: asp.net api entity-framework asp.net-web-api


【解决方案1】:

当您尝试在 c# 中使用任何为 null 的值时,您将收到“对象引用错误”。您需要查看 API 调用方法来检查 emp 为何变为 null。 以下是可能性-

  • 从调用方法传递的参数名称应与 API 参数中的名称完全相同,在您的情况下应为 emp。
  • 检查您的员工模型是否与您的调用方法属性匹配。

您可以从浏览器的“网络”选项卡中查看此信息。

【讨论】:

    猜你喜欢
    • 2016-12-29
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多