今天小編給大家分享一下.NET中間件與VUE攔截器聯(lián)合使用的方法是什么的相關(guān)知識點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
我們提供的服務(wù)有:網(wǎng)站建設(shè)、成都做網(wǎng)站、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、若羌ssl等。為成百上千企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的若羌網(wǎng)站制作公司
特性:
//特性 public class ModelEsignNameAttribute : Attribute { public ModelEsignNameAttribute(string nameProp, string id, string reversion = "", ModelESignType eSignType = ModelESignType.Modeling, string middleModelId = "") { } }
接口加上特性:
////// 添加或者修改方法 /// /// /////特性上添加參數(shù)的地址 [ModelEsignName("Bolg.BolgBaseEditDto.BolgName", "Document.Id", "Bolg.BolgRevision")] public async Task
中間件代碼:
namespace GCT.MedPro.Middleware { public class ModelESignCheckMiddleware : IMiddleware { #region 依賴注入等內(nèi)容 .... #endregion public async Task InvokeAsync(HttpContext context, RequestDelegate next) { if (await ShouldCheckESign(context)) { // 不需要電子簽名 await next(context); } } ////// 是否需要攔截 /// /// ///private async Task ShouldCheckESign(HttpContext actionContext) { var whetherSignature = true; var request = actionContext.Request;//獲取請求值 var currentUser = actionContext.User.Identity.Name; var serviceAction = actionContext .GetEndpoint()? .Metadata .GetMetadata (); if (serviceAction == null) { return whetherSignature; } //通過接口特性來篩選是否需要進(jìn)行攔截 var attrObj = serviceAction.MethodInfo.CustomAttributes .FirstOrDefault(x => x.AttributeType == typeof(ModelEsignNameAttribute)); if (attrObj == null) { return whetherSignature; } string inputbody = default; actionContext.Request.EnableBuffering(); //Post請求獲取請求參數(shù),轉(zhuǎn)換JSON if (request.Method.ToLower().Equals("post")) { var requestReader = new StreamReader(actionContext.Request.Body); var body = await requestReader.ReadToEndAsync(); inputbody = UpperFirst(body); //首字母大寫 全局搜索可得下方有 } else //GET請求以及其他方式獲取 { var reqString = request.QueryString.Value.Remove(0, 1); string[] parts = reqString.Split("&"); JObject json = new JObject(); foreach (string part in parts) { String[] keyVal = part.Split("="); json.Add(keyVal[0], keyVal[1]); } inputbody = JsonConvert.SerializeObject(json); inputbody = UpperFirst(inputbody); } var inputObj = JObject.Parse(inputbody);//轉(zhuǎn)換JObject #region 獲取特性傳入的參數(shù),,總五位參數(shù) var actionName = serviceAction.ActionName; var namePath = attrObj.ConstructorArguments[0].Value.ToString(); var idPath = attrObj.ConstructorArguments[1].Value.ToString(); var revsionPath = attrObj.ConstructorArguments[2].Value.ToString(); var typePath = (ModelESignType)attrObj.ConstructorArguments[3].Value; var middlePath = attrObj.ConstructorArguments[4].Value.ToString(); #endregion var middleModelId = GetValueName(inputObj, middlePath);//通過JObject獲取對應(yīng)值 //接口控制器名稱 var typeName = serviceAction.ControllerTypeInfo.FullName; //重置請求Body指針 actionContext.Request.Body.Position = 0; //驗(yàn)證方法,自己寫個(gè),自已業(yè)務(wù)的處理驗(yàn)證 var output = await CheckSign(middleModelId); if (!output.SignStatus) { actionContext.Request.EnableBuffering(); Stream originalBody = actionContext.Response.Body; try { using (var ms = new MemoryStream()) { //修改響應(yīng)狀態(tài)麻420 actionContext.Response.Body = ms; actionContext.Response.StatusCode = 420; ms.Position = 0; //寫入數(shù)據(jù) var responseBody = TextJosn.JsonSerializer.Serialize(output); var memoryStream = new MemoryStream(); var sw = new StreamWriter(memoryStream); //自己編輯的實(shí)體寫入響應(yīng)體 sw.Write(responseBody); sw.Flush(); //重置響應(yīng)指針 memoryStream.Position = 0; //復(fù)制到原body上 await memoryStream.CopyToAsync(originalBody); } } finally { actionContext.Response.Body = originalBody; actionContext.Request.Body.Position = 0; } whetherSignature = false; } else { if (!string.IsNullOrWhiteSpace(output.ErrorMessage)) { var serializerSettings = new JsonSerializerSettings { // 設(shè)置為駝峰命名 ContractResolver = new Newtonsoft.Json.Serialization .CamelCasePropertyNamesContractResolver() }; //錯(cuò)誤友好提示,適配中間件中拋出錯(cuò)誤,修改響應(yīng)體 var exception = new UserFriendlyException(output.ErrorMessage); actionContext.Response.StatusCode = 500; actionContext.Response.ContentType = "application/json; charset=utf-8"; //寫入 await actionContext.Response.WriteAsync( JsonConvert.SerializeObject( new AjaxResponse( _errorInfoBuilder.BuildForException(exception), true ), serializerSettings ) ); whetherSignature = false; } } return whetherSignature; } //取出json的Name值 private string GetValueName(JObject inputObj, string path) { string result = null; if (!string.IsNullOrWhiteSpace(path)) { result = inputObj.SelectToken(path).ToObject (); } return result; } /// /// Json字符串首字母轉(zhuǎn)大寫 /// /// json字符串 ///public static string UpperFirst(string strJsonData) { MatchCollection matchCollection = Regex.Matches(strJsonData, "\\\"[a-zA-Z0-9]+\\\"\\s*:"); foreach (Match item in matchCollection) { string res = Regex.Replace(item.Value, @"\b[a-z]\w+", delegate (Match match) { string val = match.ToString(); return char.ToUpper(val[0]) + val.Substring(1); }); strJsonData = strJsonData.Replace(item.Value, res); } return strJsonData; } } }
Vue攔截器,攔截失敗的響應(yīng),狀態(tài)碼為420的,中間件修改的響應(yīng)的狀態(tài)碼:
import { AppConsts } from '/@/abpPro/AppConsts'; import { abpService } from '/@/shared/abp'; import { Modal } from 'ant-design-vue'; import axios, { AxiosResponse } from 'axios'; import abpHttpConfiguration from './abp-http-configuration.service'; const apiHttpClient = axios.create({ baseURL: AppConsts.remoteServiceBaseUrl, timeout: 300000, }); // 請求攔截器 apiHttpClient.interceptors.request.use( (config: any) => { // .... return config; }, (error: any) => { return Promise.reject(error); }, ); // 響應(yīng)攔截器 apiHttpClient.interceptors.response.use( (response: AxiosResponse) => { // 響應(yīng)成功攔截器 if (response.data.__abp) { response.data = response.data.result; } return response; }, (error: any) => { // 響應(yīng)失敗攔截器 //方法里存在異步,使用一個(gè)Promise包裹起來 return new Promise((resolve, reject) => { // 關(guān)閉所有模態(tài)框 Modal.destroyAll(); const errorResponse = error.response; const ajaxResponse = abpHttpConfiguration.getAbpAjaxResponseOrNull(error.response); if (ajaxResponse != null) { abpHttpConfiguration.handleAbpResponse(errorResponse, ajaxResponse); reject(error); } else { if (errorResponse.status == 420) { //abpHttpConfiguration中自己寫的一個(gè)模態(tài)框彈窗,把響應(yīng)數(shù)據(jù)傳入其中 abpHttpConfiguration.needIntercept(errorResponse.data) .toPromise()//Observable轉(zhuǎn)Promise .then((value) => { if (value) { // resolve 原先的請求地址,重發(fā)請求 resolve(apiHttpClient(errorResponse.config)); } else { reject(error); } }); } else { abpHttpConfiguration.handleNonAbpErrorResponse(errorResponse); reject(error); } } }); }, ); export default apiHttpClient;
模態(tài)框彈窗,返回的bool類型:
//是否驗(yàn)證需求通過彈窗 needIntercept(error): Observable{ return new Observable ((obs) => { if (error != undefined && error.SignStatus != null && !error.SignStatus) { //彈出模態(tài)框 this.modalCreate(error).subscribe( (b) => { obs.next(b); obs.complete(); }, (error) => console.log(error, 123), () => { obs.next(false); obs.complete(); }, ); } else { obs.next(false); obs.complete(); } }); } //電子簽名彈窗 modalCreate(responseBody: any): Observable { let sub; if (!responseBody.IsAccountSign) { //彈出模態(tài)框,指定的組件GESignNameComponent ,傳入?yún)?shù) sub = modalHelper.create( GESignNameComponent, { relationId: responseBody.ModelSignNameId, listEsignRequirementId: responseBody.ListSignRequirementId, }, ); } else { //彈出模態(tài)框,GESignNameAccountComponent ,傳入?yún)?shù) sub = modalHelper.create( GESignNameAccountComponent, { relationId: responseBody.ModelSignNameId, listEsignRequirementId: responseBody.ListSignRequirementId, }, ); } return sub; }
以上就是“.NET中間件與VUE攔截器聯(lián)合使用的方法是什么”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。