/// <summary> /// 处理输出状态码 /// </summary> /// <param name="context"></param> /// <param name="statusCode"></param> /// <returns></returns> public async Task OnResponseStatusCodes(HttpContext context, int statusCode) { switch (statusCode) { // 处理 401 状态码 case StatusCodes.Status401Unauthorized: await context.Response.WriteAsJsonAsync(new RESTfulResult <object> { StatusCode = StatusCodes.Status401Unauthorized, Successed = false, Data = null, Errors = "401 Unauthorized", Extras = UnifyResultContext.Take() }, JsonSerializerUtility.GetDefaultJsonSerializerOptions()); break; // 处理 403 状态码 case StatusCodes.Status403Forbidden: await context.Response.WriteAsJsonAsync(new RESTfulResult <object> { StatusCode = StatusCodes.Status403Forbidden, Successed = false, Data = null, Errors = "403 Forbidden", Extras = UnifyResultContext.Take() }, JsonSerializerUtility.GetDefaultJsonSerializerOptions()); break; default: break; } }
/// <summary> /// 发送 Http 请求 /// </summary> /// <param name="requestUri"></param> /// <param name="httpMethod"></param> /// <param name="bodyArgs"></param> /// <param name="headers"></param> /// <param name="clientName"></param> /// <param name="interceptor"></param> /// <param name="contentType"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task <T> SendAsAsync <T>(this string requestUri, HttpMethod httpMethod = default, object bodyArgs = null, Dictionary <string, string> headers = default, string clientName = default, Action <HttpRequestMessage> interceptor = default, string contentType = "application/json", CancellationToken cancellationToken = default) { var response = await requestUri.SendAsync(httpMethod, bodyArgs, headers, clientName, interceptor, contentType, cancellationToken); // 读取流 using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken); // 反序列化结果 var result = await JsonSerializer.DeserializeAsync <T>(responseStream, JsonSerializerUtility.GetDefaultJsonSerializerOptions(), cancellationToken); return(result); }
/// <summary> /// 处理输出状态码 /// </summary> /// <param name="context"></param> /// <param name="statusCode"></param> /// <returns></returns> public async Task OnResponseStatusCodes(HttpContext context, int statusCode) { switch (statusCode) { // 处理 401 状态码 case StatusCodes.Status401Unauthorized: await context.Response.WriteAsJsonAsync(new ApiResponse <object> { Code = StatusCodes.Status401Unauthorized, Success = false, Data = null, Msg = "401 Unauthorized", Extras = UnifyContext.Take(), Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }, JsonSerializerUtility.GetDefaultJsonSerializerOptions()); break; // 处理 403 状态码 case StatusCodes.Status403Forbidden: await context.Response.WriteAsJsonAsync(new ApiResponse <object> { Code = StatusCodes.Status403Forbidden, Success = false, Data = null, Msg = "403 Forbidden", Extras = UnifyContext.Take(), Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }, JsonSerializerUtility.GetDefaultJsonSerializerOptions()); break; default: break; } }
/// <summary> /// 拦截异步带返回值方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="method"></param> /// <param name="args"></param> /// <returns></returns> public override async Task <T> InvokeAsyncT <T>(MethodInfo method, object[] args) { // 发送请求 var(response, httpMethodAttribute) = await SendAsync(method, args); // 判断是否请求成功 if (response.IsSuccessStatusCode) { // 打印成功消息 App.PrintToMiniProfiler(MiniProfilerCategory, "Succeeded"); // 处理返回值类型 switch (httpMethodAttribute.ResponseType) { // 对象类型或流类型 case ResponseType.Object: case ResponseType.Stream: var responseStream = await response.Content.ReadAsStreamAsync(); // 流类型 if (httpMethodAttribute.ResponseType == ResponseType.Stream) { return((T)(object)responseStream); } // 对象类型 else { var result = await JsonSerializer.DeserializeAsync <T>(responseStream, JsonSerializerUtility.GetDefaultJsonSerializerOptions()); // 释放流 await responseStream.DisposeAsync(); return(result); } // 文本类型 case ResponseType.Text: var responseText = await response.Content.ReadAsStringAsync(); return((T)(object)responseText); // Byte 数组类型 case ResponseType.ByteArray: var responseByteArray = await response.Content.ReadAsByteArrayAsync(); return((T)(object)responseByteArray); // 无效类型 default: throw new InvalidCastException("Invalid response type setting."); } } else { throw (await CreateRequestException(response)); } }
/// <summary> /// 设置方法体 /// </summary> /// <param name="request"></param> /// <param name="bodyArgs"></param> /// <param name="bodyContentTypeOptions"></param> /// <param name="jsonNamingPolicyOptions"></param> /// <param name="contentType"></param> internal static void SetHttpRequestBody(HttpRequestMessage request, object bodyArgs, HttpContentTypeOptions bodyContentTypeOptions, JsonNamingPolicyOptions jsonNamingPolicyOptions, string contentType) { // 处理 body 内容 HttpContent httpContent; switch (bodyContentTypeOptions) { case HttpContentTypeOptions.StringContent: case HttpContentTypeOptions.JsonStringContent: case HttpContentTypeOptions.XmlStringContent: string bodyContent; // application/json;text/json;application/*+json if (bodyContentTypeOptions == HttpContentTypeOptions.JsonStringContent) { // 配置 Json 命名策略 var jsonSerializerOptions = JsonSerializerUtility.GetDefaultJsonSerializerOptions(); jsonSerializerOptions.PropertyNamingPolicy = jsonNamingPolicyOptions switch { JsonNamingPolicyOptions.CamelCase => JsonNamingPolicy.CamelCase, JsonNamingPolicyOptions.Null => null, _ => null }; bodyContent = JsonSerializerUtility.Serialize(bodyArgs, jsonSerializerOptions); } // application/xml;text/xml;application/*+xml else if (bodyContentTypeOptions == HttpContentTypeOptions.XmlStringContent) { var xmlSerializer = new XmlSerializer(bodyArgs.GetType()); var buffer = new StringBuilder(); using var writer = new StringWriter(buffer); xmlSerializer.Serialize(writer, bodyArgs); bodyContent = buffer.ToString(); } // none else { bodyContent = bodyArgs.ToString(); } httpContent = new StringContent(bodyContent, Encoding.UTF8); break; // 处理 x-www-form-urlencoded case HttpContentTypeOptions.FormUrlEncodedContent: Dictionary <string, string> formDataDic = new(); if (bodyArgs is Dictionary <string, string> dic) { formDataDic = dic; } else { var bodyArgsType = bodyArgs.GetType(); // 只有类和匿名类才处理 if (bodyArgsType.IsClass || bodyArgsType.IsAnonymous()) { var properties = bodyArgsType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { formDataDic.Add(prop.Name, prop.GetValue(bodyArgs)?.ToString()); } } } httpContent = new FormUrlEncodedContent(formDataDic); break; // 处理 multipart/form-data case HttpContentTypeOptions.MultipartFormDataContent: default: throw new NotImplementedException("Please use RequestInterceptor to set."); } // 设置内容 if (httpContent != null) { httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Content = httpContent; } }