借助中間件自動化文檔
編寫這個中間件的理由:
- 常見的自動化文檔庫,比如swagger,只能依賴于XML注釋.這種文檔,生成的數(shù)據(jù)樣本單一,而且與代碼脫節(jié)改起來非常討厭.
- 為了裝逼.
使用方法
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
var container = new CompositionContainer(new ApplicationCatalog(), true);
config.Services.Replace(typeof(IContentNegotiator), new CustomJsonContentNegotiator());
config.Services.Replace(typeof(IHttpControllerActivator), new CustomControllerActivator(container));//MEF,IOC容器注入
config.MapHttpAttributeRoutes();
app.UseCors(CorsOptions.AllowAll);//使用Cors開啟跨域,這里為了方便,直接AllowAll了
app.UseWebApi(config);
app.Use<WebApiDocumenting.WebApiDocumenting>(config);//看這里,Use一個中間件即可,是不是很簡單?對業(yè)務(wù)代碼,幾乎0侵染性
}
}
//然后就會生出一個json,這里我用VueJs做了界面,基于當時Vue組件還不是很多,所以弄的一般般(主要沒有做前端路由),就不放出來獻丑了.
//你也可以在DTO中的屬性,DTO的類名,Action中添加注解,會生出對應(yīng)包含注釋的json.
[Description("創(chuàng)建新聞")]
public class CreateNewsInfo
{
public string Title { get; set; }
[Name]//目前框架提供的注解不是很多,主要是,要提供非常完美的數(shù)據(jù)樣本,必須依托于巨大數(shù)據(jù)庫.懶得弄
public string Introduction { get; set; }
[Description("新聞類型")]//目前框架提供的注解不是很多,主要是,要提供非常完美的數(shù)據(jù)樣本,必須依托于巨大數(shù)據(jù)庫.懶得弄
public int Type { get; set; }
public bool IsHidden { get; set; }
public bool IsTop { get; set; }
public string Icon { get; set; }
public string Content { get; set; }
}
文檔中間件項目介紹
承接上一章的內(nèi)容,我現(xiàn)在要寫一個中間件,輸出所有的ApiInfo.怎么做?
- 我的中間件里默認傳入的數(shù)據(jù)是OwinContext(由Adapter轉(zhuǎn)化成了HttpContxt而來),
我要知道程序集相關(guān)的內(nèi)容,就必須從HttpConfiguration反射出來
所以中間件的構(gòu)造注入一個HttpConfiguration
public class WebApiDocumenting : OwinMiddleware
{
private readonly HttpConfiguration _configuration;
public WebApiDocumenting(OwinMiddleware next, HttpConfiguration configuration)
: base(next)
{
_configuration = configuration;
}
public override async Task Invoke(IOwinContext context)
{
//這里根據(jù)_configuration獲取所有Api信息
if (!IsDocumentRequest(context))
{
await Next.Invoke(context);
return;
}
//傳入HttpConfiguration構(gòu)造我需要的數(shù)據(jù),具體詳情請見代碼.這里僅介紹中間件的使用
var siteInfoBuilder = new SiteInfoBuilder(_configuration);
var siteInfo = siteInfoBuilder.Build();
var json = JsonConvert.SerializeObject(siteInfo, new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
context.Response.Write(json);
context.Response.ContentType = "application/json;charset=utf-8";
}
private static bool IsDocumentRequest(IOwinContext context)
{
return string.Compare(context.Request.Path.Value, "/$document", StringComparison.OrdinalIgnoreCase) == 0;
}
}
根據(jù)HttpConfiguration反射出所有的信息,具體請看源碼
修改Json.net配置,讓其生成可以注釋的json,具體請看源碼
源碼地址:https://github.com/songtinHuang/Songtin.AutoDocument
啊,折騰好久,終于在VS2013上裝好github插件了,下一步就是買github外套假裝自己是geeker了.
呵呵.