如何在一个WebApi中拥有两个DELETE签名,如下面的代码?
public HttpResponseMessage Delete(int id)
{
if (id < 1) { return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "ID cannot be null" }); };
try
{
GenericCatalogManagerBL.DeletePart(_genericCNN, id);
return Request.CreateResponse(HttpStatusCode.Accepted, new { msg = "Part removed" });
}
catch (Exception)
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "Part not removed" });
}
}
public HttpResponseMessage Delete(int genericCatalogID)
{
if (genericCatalogID < 1) { return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "GenericCatalogID cannot be null" }); };
try
{
GenericCatalogManagerBL.DeletePartsAll(_genericCNN, genericCatalogID);
return Request.CreateResponse(HttpStatusCode.Accepted, new { msg = "Parts removed" });
}
catch (Exception)
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "Parts not removed" });
}
}
答案 0 :(得分:3)
您的示例违反了重载规则,必须有一些区别的签名。除了添加另一个参数之外,唯一的解决方案是重命名您的一个方法。
答案 1 :(得分:2)
public HttpResponseMessage Delete(int id)
{
if (id < 1) { return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "ID cannot be null" }); };
try
{
GenericCatalogManagerBL.DeletePart(_genericCNN, id);
return Request.CreateResponse(HttpStatusCode.Accepted, new { msg = "Part removed" });
}
catch (Exception)
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "Part not removed" });
}
}
public HttpResponseMessage DeleteByCatalogID(int genericCatalogID)
{
if (genericCatalogID < 1) { return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "GenericCatalogID cannot be null" }); };
try
{
GenericCatalogManagerBL.DeletePartsAll(_genericCNN, genericCatalogID);
return Request.CreateResponse(HttpStatusCode.Accepted, new { msg = "Parts removed" });
}
catch (Exception)
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, new { msg = "Parts not removed" });
}
并相应地映射路线...
答案 2 :(得分:0)
在你在这里讨论的级别,你的问题是你无法区分这两者。
在实际的HTTP请求级别,你会遇到同样的问题; DELETE
到URI意味着删除该URI表示的资源;没有“不同类型的删除”,它被删除了。
但是,没有理由说一个资源不能代表另一个资源或一组资源的部分或全部功能。使用单独的URI定义资源以表示(以及C#级别的类),并区分您尝试删除的对象类型的删除。或者,将DELETE
映射到特定的URI模式到不同的方法。
答案 3 :(得分:0)
您不能拥有两个具有相同签名的操作。但是,您可以使用以下内容:
public HttpResponseMessage Delete(int? id, int? genericCatalogID)
{
// Your logic here
}
如果两个参数都有值,您只需要考虑会发生什么。