【问题标题】:call to DELETE api does not work on Postman调用 DELETE api 在 Postman 上不起作用
【发布时间】:2020-12-28 23:01:58
【问题描述】:

GET / POST / PUT,API 调用在 Postman 上工作。

普通删除或自定义删除不会。

一个。常规删除

Postman 中的 URL 调用 - http://localhost:59510/api/Employee/123

邮递员中的错误 -

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:59510/api/Employee/123'.",
    "MessageDetail": "No action was found on the controller 'Employee' that matches the request."
}

代码:

[HttpDelete]
public string Delete(int empID)
{
    try
    {
        string sSQL = $@"DELETE dbo.Employee WHERE emp_id='J-L12345M'";

        DataTable dt = new DataTable();

        using (var connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["WebAPIConn"].ConnectionString))
        {
            using (var cmd = new SqlCommand(sSQL, connStr))
            {
                using (var da = new SqlDataAdapter(cmd))
                {
                    cmd.CommandType = CommandType.Text;
                    da.Fill(dt);
                }

            }
        }

        return "Deleted Successfully From EMPLOYEE table!!";
    }
    catch
    {
        return "Failed to Delete From EMPLOYEE table";
    }
}

b.自定义删除

Postman 中的 URL 调用 - http://localhost:59510/api/Employee/DeleteEmployee/123

邮递员错误 - 404 错误

[Route("api/Employee/DeleteEmployee")]
[HttpDelete]
public string DeleteEmployee(int empID)
{
    try
    {
        string sSQL = $@"DELETE dbo.Employee WHERE emp_id='{empID}'";

        DataTable dt = new DataTable();

        using (var connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["WebAPIConn"].ConnectionString))
        {
            using (var cmd = new SqlCommand(sSQL, connStr))
            {
                using (var da = new SqlDataAdapter(cmd))
                {
                    cmd.CommandType = CommandType.Text;
                    da.Fill(dt);
                }

            }
        }

        return "Deleted Successfully From EMPLOYEE table!!";
    }
    catch
    {
        return "Failed to Delete From EMPLOYEE table";
    }
}

【问题讨论】:

  • 你试过[Route("api/Employee/DeleteEmployee/{emdID}")]?
  • 你能发布你的整个控制器代码吗?您是否在自定义删除时在邮递员中使用 DELETE 动词?如果您为“api/Employee”的控制器定义了一个路由,那么您方法上的路由应该只是“DeleteEmployee”,否则您的自定义删除方法的实际路由是“api/Employee/api/Employee/DeleteEmployee”。
  • 注意,不要这样做:string sSQL = $@"DELETE dbo.Employee WHERE emp_id='{empID}'"; 特别是如果你有一天制作了一个控制器,它需要一个string empID - bobby-tables.com
  • 我认为问题出在属性名称上。它应该是 id 而不是 empId。如果要使用empId,请确保使用属性路由并定义与上面提到的变量名称匹配的路径。
  • FWIW,您的 URI 包含“删除”一词的事实意味着您的 URI 设计需要工作:-)。

标签: c# json http asp.net-web-api postman


【解决方案1】:

尝试将empID 添加到路由

[Route("api/Employee/DeleteEmployee/{empID}")]
[HttpDelete]
public string DeleteEmployee(int empID)

【讨论】:

  • [Route("api/Employee/DeleteEmployee/{empID}")] 确实有效。
  • Grad 它对你有用.. 你可以把这个作为答案
猜你喜欢
  • 2021-09-13
  • 1970-01-01
  • 2020-07-04
  • 2019-12-05
  • 1970-01-01
  • 2021-02-11
  • 2021-10-05
  • 2023-01-03
  • 2019-12-09
相关资源
最近更新 更多