我正在使用HttpClient使用以下代码查询WebApi控制器:
var uri = new Uri(url);
var message = new HttpRequestMessage(method, uri);
if (content != null) message.Content = new StringContent(content, Encoding.UTF8, "application/json");
var client = new HttpClient();
if (content != null) Debug.WriteLine($"Payload:\n {content}");
var response = await client.SendAsync(message);
return response;
生成的Url如下: http://localhost:9333/api/roles?$滤波器=%20Name%20当量%20'Some%20Role'/
请注意尾随'/'。这会导致OData验证(下面的代码)失败:
[HttpGet]
[Route("")]
public async Task<IHttpActionResult> GetRoles(ODataQueryOptions<RoleSummaryDto> options)
{
GuardForODataException(options);
var filteredResults = await _roleService.GetRolesAsync(options);
return Ok(filteredResults);
}
public void GuardForODataException<T>(ODataQueryOptions<T> options)
{
try
{
var validationSettings = new ODataValidationSettings();
options.Validate(validationSettings);
}
catch (Exception e)
{
var result =
new ValidationFailedResult(
Request,
new ValidationResultModel(
new ValidationResult(
new List<ValidationFailure> { new ValidationFailure("", "Odata Query is invalid") })));
throw new HttpResponseException(result.ExecuteAsync(default(CancellationToken)).Result);
}
}
我得到的例外是
“预计在第9位有一个标识符。”
但是,如果我删除尾随/,则odata查询返回预期结果。
关于如何在没有/的情况下构建HttpRequestMessage
,我找不到多少。有没有人遇到过这个?