[英]OData filter with "and" operator not working in Web Api
我正在創建一個帶有單個 GET 操作的 Web Api,它處理以下 get 請求。
GET https://localhost:44378/v1/RoutePrefix/Route ?$filter=Id eq '1234'$select=Name (這個工作正常)
GET https://localhost:44378/v1/RoutePrefix/Route ?$filter=Id eq '1234' 或 MessageType eq '1' (這很好用)
GET https://localhost:44378/v1/RoutePrefix/Route ?$filter=Id eq '1234' and MessageType eq '1' (這個不起作用。響應值總是 [])
看起來帶有“and”運算符的過濾器不起作用。 “或”運算符對我來說很好用。
我的 webapiconfig.cs 中有以下代碼。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.MapODataServiceRoute("odata", "v1/RoutePrefix", GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "Default";
builder.ContainerName = "DefaultContainer";
builder.EntitySet<Model>("Route");
builder.EntitySet<Model>("Route").EntityType.Filter(nameof(Model.Id));
builder.EntitySet<Model>("Route").EntityType.Filter(nameof(Model.MessageType));
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
在我的控制器中,根據過濾器參數的數量,我調用了不同的方法。 並且這兩種方法都返回 List 作為對 GET 方法的響應。 在 Main get 方法中,我以 Ok(List.AsQueryable()) 的形式返回。
我用 [EnableQuery] 屬性裝飾控制器並實現 ODataController 如下:
[EnableQuery] 公共類 RouteController : ODataController
Get 方法如下所示:
public IHttpActionResult Get()
{
List<Model> response = null;
string cacheKey = string.Empty;
var queryString = Request.RequestUri.PathAndQuery.Replace("/v1/RoutePrefix", "");
var queryTokens = ParseQueryString(EdmModel, queryString);
if (queryTokens == null || queryTokens.Any(a => string.IsNullOrWhiteSpace(a.Value)) || !queryTokens.ContainsKey(Constants.Id))
{
IList<ApiError> errors = new List<ApiError>() { new ApiError(Constants.InvalidQueryStringErrorCode, Constants.InvalidQueryStringErrorMessage) };
return GenerateResponse(Request, HttpStatusCode.BadRequest, errors, null);
}
else
{
try
{
if (queryTokens.ContainsKey(Constants.MessageType))
{
response = GetConfigurationByMessageTypeAndId(queryTokens);
}
else
{
response = GetConfigurationById(queryTokens);
}
}
catch (Exception ex)
{
var apiError = Utilities.CreateApiError(Constants.InternalServerError, Constants.InternalServerErrorMessage, null, null, null);
IList<ApiError> apiErrors = new List<ApiError> { apiError };
return GenerateResponse(Request, HttpStatusCode.InternalServerError, apiErrors, null);
}
if (response.Count > 0)
{
return Ok(response.AsQueryable());
}
else
{
return NotFound();
}
}
}
請讓我知道我做錯了什么。
謝謝
問題已解決。$filter 系統查詢選項允許客戶端過濾由請求 URL 尋址的資源集合。 使用 $filter 指定的表達式會針對集合中的每個資源進行計算,並且只有表達式計算結果為 true 的項目才會包含在響應中。 表達式計算結果為 false 或 null 的資源,或者由於權限而無法使用的引用屬性,將從響應中省略。我的最終集合沒有在查詢字符串中傳遞的原始值。 它被替換為不同的值 – Kumaraguru 1 分鍾前編輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.