Asp.net-Web-Api

將任意數據添加到 WebAPI 中的 OData 元數據?

  • December 6, 2018

我有一個使用 OData ( System.Web.Http.OData, 5.1.0.0) 的簡單 WebAPI2 服務。使用者可以點擊/odata/$metadata獲取可用的實體和屬性。我正在尋找一種使用附加資訊擴展此元數據的方法,例如向屬性添加“顯示名稱”值。

我發現有關“註釋”的資訊聽起來像是我想要的,但我找不到任何解釋如何在我的場景中使用它的資訊,或者它是否可能。我試圖做類似以下的事情:

model.SetAnnotationValue(((IEdmEntityType)m.FindType("My.Thing")).FindProperty("SomeProperty"),
      namespaceName:"MyNamespace",
      localName: "SomeLocalName",
      value: "THINGS");

類型/屬性名稱正確且呼叫成功,但 OData EDMX 文件不包含此註釋。有什麼方法可以公開這些註釋或做我想做的事嗎?

更新

還在。我一直在尋找ODataMediaTypeFormatters一種可能的方法來處理這個問題。有一個ASP.NET 範例項目展示瞭如何向實體添加實例註釋。關閉,但不完全是我想要的,所以現在我試圖找到一種方法來擴展以類似方式生成元數據文件的任何內容。

我想出了一個辦法來做到這一點。下面的程式碼添加了一個自定義命名空間前綴“myns”,然後在模型屬性上添加了一個註解:

const string namespaceName = "http://my.org/schema";
var type = "My.Domain.Person";
const string localName = "MyCustomAttribute";

// this registers a "myns" namespace on the model
model.SetNamespacePrefixMappings(new [] { new KeyValuePair<string, string>("myns", namespaceName), });

// set a simple string as the value of the "MyCustomAttribute" annotation on the "RevisionDate" property
var stringType = EdmCoreModel.Instance.GetString(true);
var value = new EdmStringConstant(stringType, "BUTTONS!!!");
m.SetAnnotationValue(((IEdmEntityType) m.FindType(type)).FindProperty("RevisionDate"),
                       namespaceName, localName, value);

請求 OData 元數據文件應為您提供如下資訊:

<edmx:Edmx Version="1.0">
   <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0">
       <Schema Namespace="My.Domain">
           <EntityType Name="Person">
               <Key><PropertyRef Name="PersonId"/></Key>
               <Property Name="RevisionDate" Type="Edm.Int32" Nullable="false" myns:MyCustomAttribute="BUTTONS!!!"/>
       </Schema>
   </edmx:DataServices>
</edmx:Edmx>

引用自:https://stackoverflow.com/questions/22207249