【发布时间】:2018-04-08 01:11:47
【问题描述】:
我有一个网络方法来删除家具或他的一个属性:
[Authorize]
[Route("api/furniture/{furnitureId}/{property?}")]
public HttpResponseMessage Delete(string furnitureId, string property = null)
{
try
{
if (property != null)
_furnitureService.DeleteFurnitureProperty(furnitureId, property);
else
_furnitureService.DeleteFurniture(furnitureId);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
return Request.CreateResponse(HttpStatusCode.Accepted);
}
当进行正确的调用时,它会按预期工作:
- /api/furniture/id01 - 删除家具 id01
- /api/furniture/id01/p001 - 删除家具 id01 上的属性 p001
- /api/furniture/id01?property=p001 - 同时删除属性 p001 家具id01
但由于 API 使用不当,我收到了一些投诉。 例如以下调用将删除家具:
- /api/furniture/id01?prop=p001
注意它使用了错误的 prop 参数名称,而不是 property
我知道他们有呼叫错误,但删除家具有一些影响,需要我方预防(也可以恢复,但需要消费者采取更多步骤)
所以,我的问题是:当调用者使用任何其他参数而不是允许的参数时,我能否轻松检测和限制?这样我可以返回 400 错误而不是删除家具。 如果没有直接的方法,请推荐更简单的方法(如 Request.Params 对象正则表达式?)
【问题讨论】:
-
用
this.Request.GetQueryNameValuePairs()之类的东西解析查询字符串并在那里检查错误的键?在动作过滤器的帮助下完成了同样的操作:stackoverflow.com/a/37789473/5311735 -
谢谢,我查过了。将在我的情况下工作。我希望框架已经提供了一些东西
-
请注意,它与提供的答案不同(我会说更好),因为不需要您对有效的查询参数进行硬编码。
标签: c# asp.net rest asp.net-web-api