![](/img/trans.png)
[英]How to expose a custom generic type as a string in Swagger schema using Swashbuckle.AspNetCore
[英]AspNetCore Swagger/Swashbuckle how to modify xml schema requests
我已經在我的AspNetCore 2.1應用程序中實現了Swagger / Swashbuckle,並且運行良好。 但是,我的一些API模型基於復雜的WCF XML服務,並使用一些System.Xml.Serialization注釋來添加名稱空間和更改屬性名稱。 在Swagger頁面上查看這些模型時,它們缺少名稱空間,並忽略任何屬性名稱更改。 因此,迅速的默認請求在發布到我的控制器時不會反序列化。 另一方面,JSON請求可以正常工作。
考慮這兩類;
public class test
{
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.example.com/ns/v1")]
public test_c ct1 { get; set; }
public string t2 { get; set; }
}
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.example.com/ns/v1")]
public class test_c
{
[System.Xml.Serialization.XmlElementAttribute("my-new-name")]
public string tc1 { get; set; }
public string tc2 { get; set; }
}
當序列化為XML時,我們得到類似:
<?xml version="1.0" encoding="UTF-8"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ct1 xmlns="http://www.example.com/ns/v1">
<my-new-name>aaa</my-new-name>
<tc2>xxxxxx</tc2>
</ct1>
<t2>bbb</t2>
</test>
這是期望作為請求的xml。 但是,招搖的樣本請求顯示為;
<?xml version="1.0" encoding="UTF-8"?>
<test>
<ct1>
<tc1>string</tc1>
<tc2>string</tc2>
</ct1>
<t2>string</t2>
</test>
發布時不會反序列化。
所以現在到了重點。 我需要/希望做的就是修改swagger請求xml模式-在不影響JSON請求模式的情況下(我什至不知道它們是-還是可以分開)。 我以為這很簡單,但是我迷失了許多花哨的選項和設置。 我希望我可以簡單地分配aspnet xml序列化程序來反序列化提供的請求對象。 還是實現ISchemaFilter或IOperationsFilter?
如果有人能指出正確的方向,我將永遠感激不已。
好吧,我會自己回答的。
我沒有最終落實ISchemaFilter。 因此,為了使用與問題相同的模型來回答此問題,我首先創建了自己的ISchemaFilter實現,並在檢查中對所需的更改進行了硬編碼(實際上,我將擁有一個很大的類和屬性字典<>變化)。 “架構”類允許我們將僅XML元數據添加到模型類或其任何屬性。
public class MyRequestISchemaFilter : ISchemaFilter
{
public void Apply(Schema schema, SchemaFilterContext context)
{
if (schema.Type == "object"){
if (context.SystemType == typeof(test_c))
{
schema.Xml = new Xml()
{
Namespace = "http://www.example.com/ns/v1"
};
foreach (var prop in schema.Properties)
{
if (prop.Key == "tc1")
{
prop.Value.Xml = new Xml()
{
Name = "my-new-name"
};
}
}
}
}
}
}
然后,在啟動時在AddSwaggerGen服務configure調用中連接此過濾器。
services.AddSwaggerGen(c =>
{
c.SchemaFilter<MyRequestISchemaFilter>();
...
這是過濾器將生成的樣本請求XML;
<?xml version="1.0" encoding="UTF-8"?>
<test>
<ct1 xmlns="http://www.example.com/ns/v1">
<my-new-name>string</my-new-name>
<tc2>string</tc2>
</ct1>
<t2>string</t2>
</test>
它缺少根級XMLSchema名稱空間,但是Schema :: Xml屬性不支持多個名稱空間。 在任何情況下,只要我不使用這些名稱空間,XML都可以反序列化。 如果添加帶有名稱空間的屬性,然后將它們設置為根元素的屬性(Xml prop會處理),則可以添加它們。 還沒有嘗試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.