我有一個Web API項目,在沒有OData支持的情況下使用了好幾年,只有標準的URL參數。支持現有Web API中的ODataQueryOptions
我現在希望爲此API添加OData支持,但由於API不是建立在可查詢模型上,因此我們打算接收ODataQueryOptions<T>
對象並將其傳遞給存儲庫。
我所能找到的關於支持OData的任何內容都假定我有可查詢的模型或過於簡單化,並簡單地告訴我如何理解ODataQueryOptions
對象。因此我無法獲得一個簡單的方法並運行。
這是我目前有。
[Route("test")]
[HttpGet]
[EnableQuery]
public IHttpActionResult Test(ODataQueryOptions<TestOptions> options)
{
var settings = new ODataValidationSettings {
AllowedFunctions = AllowedFunctions.None,
AllowedLogicalOperators = AllowedLogicalOperators.Equal,
AllowedArithmeticOperators = AllowedArithmeticOperators.None,
AllowedQueryOptions = AllowedQueryOptions.Filter
};
try
{
options.Validate(settings);
}
catch (ODataException exception)
{
return BadRequest(exception.Message);
}
var binaryOperator = options.Filter?.FilterClause?.Expression as BinaryOperatorNode;
if (binaryOperator != null)
{
var property = binaryOperator.Left as SingleValuePropertyAccessNode ?? binaryOperator.Right as SingleValuePropertyAccessNode;
var constant = binaryOperator.Left as ConstantNode ?? binaryOperator.Right as ConstantNode;
if (property?.Property != null && constant?.Value != null)
{
;
}
}
return Ok();
}
的TestOptions
類(在ODataQueryOptions<TestOptions>
PARAM)目前是一個空類:
public class TestOptions
{
}
我還添加了
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// existing code
config.AddODataQueryFilter();
}
}
然而,在從REST API調用此客戶...
{
「消息」:「發生錯誤」,
「ExceptionMessage」:「未註冊非OData HTTP路由。」,
「ExceptionType」: 「System.InvalidOperationException」,
「堆棧跟蹤」: 「......」
}
有什麼我錯過了我本來以爲我可能要註冊?在global.asax中啓用OData的方法或類似方法,但例外意味着問題是使用非OData方法,但所有其他方法仍按預期方式返回(即,沒有任何OData參與)
我認爲這裏的錯誤信息有些誤導,你需要註冊OData路由。按照這裏的說明應該讓你開始:https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an -odata-v4-endpoint – TomDoesCode
該示例基於EF模型,就像我在OP中所說的那樣,我沒有基礎模型。該示例向OData端點註冊了其模型的特定詳細信息:https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint#configure-the-odata-endpoint – awj
好的,你仍然需要建立一個模型,即使它不是通過實體框架。您的模型是否會在編譯時定義? I.E會暴露的類型和屬性是否改變? – TomDoesCode