Skip to main content
 首页 » 编程设计

c#之无法从 Web API 中的删除方法获取参数

2024年02月25日33bonelee

我有一个 web api 服务器,想实现一个删除功能:

这是函数:

    public void Delete([FromBody]string identifier) 
    { 
        ExpressLogger.LogDebug("Enter"); 
        try 
        { 
 
 
            if (Utils.IsRmhUsed()) 
            { 
 
                CustomerRmhDbRepository repo = new CustomerRmhDbRepository(); 
                repo.DelCustomer(identifier); 
            } 
            else 
            { 
                //If implement function for RMS 
            } 
        } 
        catch (Exception ex) 
        { 
            ExpressLogger.LogError(ex, ex.Message); 
            HttpResponseMessage message = new  
            HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new S  
            tringContent(ex.Message) }; 
            throw new HttpResponseException(message); 
        } 
    } 

我使用以下字符串调用 postman 的方法 http://10.0.0.129:5005/api/customer?identifier=000007

调用到达 delete 方法但变量标识符为 NULL 我试过这样:http://10.0.0.129:5005/api/customer?000007

我也试过这样使用属性:

[Route("{identifier}")] 

当我这样做时,它甚至不会“进入方法”删除。

有什么问题吗?为什么我不能从变量标识符中获取值?

请您参考如下方法:

为了匹配去掉[FromBody]属性

 http://10.0.0.129:5005/api/customer?identifier=000007 

HTTP DELETE 请求没有 BODY,模型绑定(bind)器将绑定(bind)查询字符串中的参数。

如果使用路由模板

[HttpDelete] 
[Route("{identifier}")] 
public void Delete(string identifier) { 
    //... 
} 

URL 需要看起来像

http://10.0.0.129:5005/api/customer/000007 

为了匹配路由模板