在url vs querystring中使用名称/值进行API调用?

时间:2014-03-24 13:51:06

标签: restsharp

我试图将来自硬编码网址字符串的调用转换为FORVO api (forvo.com),将请求参数逐个分配给我在C#中通过ForvoRequestClass's创建的.AddParameter method属性。 。但是当请求发出时......它将它转换为查询字符串格式,如下所示:

http://apifree.forvo.com/?key=[mykeygoeshere]&language=en&format=json&limit=1&order=rate-desc&sex=f&type=word&word=APPLE}

而不是像这样:

http://apifree.forvo.com/key/[mykeygoeshere]/language/en/format=json/limit/1/order/rate-desc/sex/f/type/word/word/APPLE

我尝试过各种方法使用RestSharp来调用它...无济于事......任何想法...... ??

1 个答案:

答案 0 :(得分:1)

好的......我相信我找到了答案。在RestSharp的github repo([1]:https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest)上,我找到了以下有用的部分:

<强> UrlSegment

  

与GetOrPost不同,此ParameterType替换了占位符值   RequestUrl:

var rq = new RestRequest("health/{entity}/status");
rq.AddParameter("entity", "s2", ParameterType.UrlSegment);
     

当请求执行时,RestSharp将尝试匹配任何请求   {placeholder},带有该名称的参数(不含{})和   用值替换它。

     

因此上面的代码导致“health / s2 / status”成为Url。

所以有了这个信息,我为Forvo的每个参数构建了我的url字符串和占位符,如下所示:

/键/ {键} /格式/ {格式} /动作/ {动作} /语言/ {语言} /性别/ {性别} /顺序/ {顺序} /限制/ {极限} /类型/ {式} /字/ {字}

我的最终代码然后进行替换是这样的:

IRestClient client = new RestClient(soundRequest.SiteUrlValue);
            request.AddParameter(soundRequest.ApiKeyName, soundRequest.ApiKeyValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.ActionName, soundRequest.ActionValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.LanguageName, soundRequest.LanguageValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.FormatName, soundRequest.FormatValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.SexName, soundRequest.SexValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.OrderName, soundRequest.OrderValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.LimitName, soundRequest.LimitValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.TypeName, soundRequest.TypeValue, ParameterType.UrlSegment);
            request.AddParameter(soundRequest.WordName, soundRequest.WordValue, ParameterType.UrlSegment);