Asp.Net Web Api尾随/导致odata查询失败

时间:2017-06-09 07:45:11

标签: c# asp.net-web-api odata

我正在使用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,我找不到多少。有没有人遇到过这个?

0 个答案:

没有答案