WebAPi的視覺化輸出模式(RabbitMQ、訊息補償相關)——所有webapi似乎都缺失的一個功能
阿新 • • 發佈:2018-12-30
public class BaseApiController : ApiController { public class ViewModel { public string Content { get; set; } public object JsonObject { get; set; } public bool Success = true; } protected bool IsView; private const string ViewQuerystring = "?v"; public ViewModel ResultModel; private const string CheckToken = "CheckToken"; private const string Token = "49BBD022-CDBF-4F94-80E4-5BCACB1192EC"; private bool _checkStatus; public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) { //驗證token if (controllerContext.Request.Headers != null && controllerContext.Request.Headers.Contains(CheckToken)) { var requestToken = controllerContext.Request.Headers.GetValues(CheckToken).FirstOrDefault(); if (requestToken != null && requestToken.Equals(Token)) { this._checkStatus = true; } } if (!_checkStatus) { var checkResult = new Task<HttpResponseMessage>(() => new HttpResponseMessage { Content = new StringContent("非法訪問,缺少token", Encoding.UTF8, "text/plain") }, cancellationToken); checkResult.Start(); return checkResult; } if (controllerContext.Request.RequestUri.Query.Equals(ViewQuerystring)) this.IsView = true; base.ExecuteAsync(controllerContext, cancellationToken); //text模式 if (this.IsView) { var textResult = new Task<HttpResponseMessage>(() => new HttpResponseMessage { Content = new StringContent(this.ResultModel.Content, Encoding.UTF8, "text/plain") }, cancellationToken); textResult.Start(); return textResult; } //json模式 var resultData = new Result<object> { Data = this.ResultModel.JsonObject, Type = this.ResultModel.Success ? ResultType.Successfully : ResultType.Failure }; var jsonResult = new Task<HttpResponseMessage>(() => new HttpResponseMessage { Content = new ObjectContent(typeof(Result), resultData, new JsonMediaTypeFormatter(), "application/json") }, cancellationToken); jsonResult.Start(); return jsonResult; } }