如何将多个参数传递给DELETE请求C#Rest API

时间:2018-03-14 10:35:34

标签: c# rest parameters asp.net-web-api2 http-delete

我需要将3个参数传递给我的API DELETE请求。这是我的代码,我尝试过。

TaskModel

public class TaskModel
{
    public int DeveloperID { get; set; }
    public int ProjectID { get; set; }
    public string WorkDate { get; set; }
}

这是一个控制器类。叫TaskController

    [Route("api/Task")]
    public void Delete(TaskModel value)
    {
        TaskPersistent tp = new TaskPersistent();
        tp.deleteTask(value);
    }

这是TaskPersistent.class

public void deleteTask(TaskModel task)
{
    try
    {
        string sqlString = "DELETE from devproj WHERE (DeveloperID, ProjectID, WorkDate) =  VALUES ('" + task.DeveloperID + "', '" + task.ProjectID + "', '" + task.WorkDate + "')"; // System.NullReferenceException throw
        MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
        cmd.ExecuteNonQuery();
        long x = cmd.LastInsertedId;
    }
    catch (MySqlException x)
    {
        int errr = x.Number;

        Console.WriteLine(errr);
    }
}

我使用这样的ARC rest客户端 http://localhost:2731/api/Task?DeveloperID=1&ProjectID=2&WorkDate="2018-03-14" 来使用此API 但是当我传递这样的参数时,API抛出异常:'System.NullReferenceException' in DeleteAPI.dll(我在代码中注释了错误发生的行)。我在这里做错了什么。

2 个答案:

答案 0 :(得分:2)

您需要通过将TaskModel作为模型活页夹的正文发布来使用此API,以便与设置Delete控制器操作的方式一起使用。或者,将Delete方法参数更改为int developerId, int projectId, DateTime workDate

    [Route("api/Task")]
    public void Delete(int developerId, int projectId, DateTime workDate)
    {
        var taskModel = new TaskModel
        {
            DeveloperId = developerId,
            ProjectID = projectId,
            WorkDate = workDate
        };
        TaskPersistent tp = new TaskPersistent();
        tp.deleteTask(taskModel);
    }

答案 1 :(得分:2)

string sqlString = "DELETE from devproj WHERE (DeveloperID, ProjectID, WorkDate) =  VALUES ('" + task.DeveloperID + "', '" + task.ProjectID + "', '" + task.WorkDate + "')"; // System.NullReferenceException throw

此查询不起作用。 SQL删除是:

string sqlString = $"DELETE from devproj WHERE DeveloperID = {task.DeveloperID} AND ProjectID = {task.ProjectID} AND WorkDate = {task.WorkDate}";

在执行查询之前,不要忘记检查模型中的空值。