这不是问题而是问题,但我仍然无法在互联网上找到答案。 当我在代码中汇编我的api URL时,我会这样:
代码:getProductId(baseUrl + "products/" + productID + "?client_id=" + clientID);
网址:https://www.testAPI/products/product123?client_id=user1
这有效,但是我很确定这不是正确的方法。 例如,如果用户可以在参数中输入除productID之外的其他内容,则可能会打乱我的电话,例如: 此api中有另一个调用/ products / productID / inventory?client_id = ...
此调用将返回整个其他对象,如果我尝试从json序列化它,它将与我的代码搞混。
我知道可以通过正文或使用后缀来提供参数,但这不是我的用例。给我的api使用url参数。
感谢任何帮助人员。
答案 0 :(得分:0)
要构造URL,应使用UriBuilder类。 您可以在这里找到文档:https://docs.microsoft.com/en-us/dotnet/api/system.uribuilder?view=netstandard-2.0
var builder = new UriBuilder();
builder.Host = "...";
builder.Path = "...";
builder.Query = "...";
但是,尽管您似乎担心有人可能会将无效数据传递给查询参数,但您应该围绕URL构造逻辑构建一个强类型包装器方法。
public Uri CreateGetProductByIdUri(Product product, Client client)
{
// Use product.Id and client.id here to construct the URL with UriBuilder
}