/// <summary> /// 获取参数 /// </summary> /// <param name="RouteData"></param> /// <param name="_objs"></param> /// <returns></returns> internal static bool GetMinObj(AshxRouteData RouteData, out object[] _objs) { Ashx ashx = RouteData.GetAshx; if (ashx.Parameters.Length > 0) { bool minObj(out object[] _objs) { int index = 0; int length = ashx.Parameters.Length; _objs = new object[length]; if (ashx.Parameters[index].ParameterType == typeof(HttpContext)) { _objs[0] = RouteData.HttpContext; index++; } _objs = AshxExtension.GetParameterObjs(ashx, RouteData.HttpContext.Request, index, length, _objs, out bool isException); return(isException); } return(minObj(out _objs)); } _objs = default; return(false); }
/// <summary> /// 初始化 /// </summary> /// <param name="httpHandler">构造的对应实现</param> /// <param name="ashxRoute">路由信息对象</param> /// <param name="objs">数据</param> internal static Task StartMinAshx(IMinHttpApi httpHandler, AshxRouteData ashxRoute, object[] objs) { //httpHandler.SetRouteData(RouteData); //RouteData.HttpContext.Response.AppendHeader(AshxVersionHeaderName, AshxVersion); httpHandler.Request(ashxRoute, objs); return(Task.CompletedTask); }
/// <summary> /// 初始化(异步) /// </summary> /// <param name="ashxRoute">路由信息对象</param> /// <param name="httpHandler">构造的对应实现</param> /// <param name="objs">数据</param> internal static async Task StartMinAsyncAshx(IMinHttpAsynApi httpHandler, AshxRouteData ashxRoute, object[] objs) { await httpHandler.TaskRequest(ashxRoute, objs) .ContinueWith((task) => { httpHandler.ContinueWith(task, ashxRoute); }); // Task.Run(() => //{ // //httpHandler.SetRouteData(RouteData); // //RouteData.HttpContext.Response.AppendHeader(AshxVersionHeaderAsyncName, AshxVersion); // using (httpHandler) // { // ; // // if (taskWrapperAsync.Task.IsFaulted) // // { // // AshxException(new AshxException(RouteData.GetAshx, new Exception("发生异常,异步处理过程中发生异常。", taskWrapperAsync.Task.Exception.GetBaseException())) { ExceptionHandled = true }); // // } // // if (!taskWrapperAsync.Task.IsCompleted) // // { // // AshxException(new AshxException(RouteData.GetAshx, new Exception("发生异常,异步处理未完成。")) { ExceptionHandled = true }); // // } // } //}); }
/// <summary> /// 验证请求结果 /// </summary> /// <param name="httpHandler"></param> /// <param name="RouteData"></param> /// <returns></returns> internal static bool Initialize(IHttpApi httpHandler, AshxRouteData RouteData) { httpHandler.SetRouteData(RouteData); RouteData.HttpContext.Response.AppendHeader(RouteData.GetAshx.IsTask ? AshxVersionHeaderAsyncName : AshxVersionHeaderName, AshxVersion); //AshxExtension.CrossDomain(RouteData.HttpContext.Response, RouteData.GetAshx); return(httpHandler.Initialize(RouteData.GetAshx)); }
/// <summary> /// 下载核心任务对象 /// </summary> /// <param name="ashxRoute">核心传输对象</param> /// <returns>返回任务</returns> public override async Task ExecuteOutAsync(AshxRouteData ashxRoute) { ashxRoute.HttpContext.Response.Headers.Add("Connection", "Keep-Alive"); ashxRoute.HttpContext.Response.Headers.Add("Content-Length", FileStream.Length.ToString()); ashxRoute.HttpContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + Name); //await ashxRoute.HttpContext.Response.Body.WriteAsync(Body.AsMemory(0, Body.Length)); //long len = (1024 * 512) > FileStream.Length ? FileStream.Length : (1024 * 512); //byte[] slice = new byte[1024 * 512]; //byte[] slice = new byte[len]; //long seekiength = 0; //do //{ // int i = await FileStream.ReadAsync(slice.AsMemory(0, slice.Length)); // await writeStream.WriteAsync(slice.AsMemory(0, i)); // await writeStream.FlushAsync(); // seekiength += i; // Array.Clear(slice, 0, i); //} while (FileStream.Length > seekiength); //await FileStream.DisposeAsync(); System.IO.Stream writeStream = ashxRoute.HttpContext.Response.Body; await HttpContextExtension.StreamMove(FileStream, writeStream, 1024 * 512); }
protected override IApiOut Initialize(AshxRouteData ashxRoute) { //if (ashxRoute.Action != "Download") //{ // return ApiOut.Redirect("Download/cs.html"); //} return(null); }
//[AshxRoute(template: "小鸟/{id?}")] //[AshxRoute(template: "小鸟/{id=cs}.html")] //public IApiOut Index([ApiVal(Val.RouteKey)] string id) //{ // "hhh".ToInt(); // return ApiOut.View(id + ".html");// ApiOut.ViewAsyn(); // //} public async Task <IApiOut> Index(string p, int a, decimal c, [ApiVal(Val.AllMode)] Api.ps app, [ApiVal(Val.RouteKey)] string d, [ApiVal(Val.Service)] AshxRouteData e, [ApiVal(Val.RouteKey)] string id = "cs") { "hhh".ToInt(); return(await ApiOut.PathViewAsync(id));// ApiOut.ViewAsyn(); // }
protected override IApiOut Initialize(AshxRouteData ashxRoute) { if (!ashxRoute.HttpContext.Session.IsAvailable) { return(ApiOut.View("500.html")); } return(RoleAction.Initialize(ashxRoute)); }
private static void IsException(AshxException ex, AshxRouteData ashxRoute, IApiOut aipOut) { if (ex.ExceptionHandled) { aipOut?.HttpOutput(ashxRoute).Wait(); } else { throw ex; } }
bool IMinHttpApi.Initialize(AshxRouteData ashxRoute) { IApiOut aipOut; bool isapi = (aipOut = Initialize(ashxRoute)) == null;//Initialize(ashxRoute, out IApiOut aipOut); if (!isapi) { aipOut?.HttpOutput(ashxRoute).Wait(); } return(isapi);//(ashxRoute.HttpContext, ashxRoute.GetAshx); }
protected override IApiOut Initialize(AshxRouteData ashxRoute) { if (dbHelper == null) { dbHelper = ashxRoute.HttpContext.GetService <DbHelper>(); ILoggerFactory loggerFactory = ashxRoute.HttpContext.GetService <ILoggerFactory>();//ILogger loggerFactory1 = context.GetService<ILogger<Share>>(); dbHelper.SetLogger(loggerFactory.CreateLogger("Sql")); } count++; return(null); }
// ///// <summary> ///// 将指定文件的内容作为文件块直接写入 HTTP 响应输出流。 ///// </summary> ///// <param name="filename">要写入 HTTP 输出的文件名。</param> ///// <exception cref="System.ArgumentNullException">filename 参数为 null。</exception> //public void WriteFile(string filename) //{ // if (Response != null) // { // Response.WriteFile(filename); // } // else // { // throw new System.Exception("请在{Ashx注入后}调用方法,使用。"); // } //} ///// <summary> ///// 将指定文件的内容作为内存块直接写入 HTTP 响应输出流。 ///// </summary> ///// <param name="filename">要写入内存块的文件名。</param> ///// <param name="readIntoMemory">指示是否将把文件写入内存块。</param> ///// <exception cref="System.ArgumentNullException">filename 参数为 null。</exception> //public void WriteFile(string filename, bool readIntoMemory) //{ // if (Response != null) // { // Response.WriteFile(filename, readIntoMemory); // } // else // { // throw new System.Exception("请在{Ashx注入后}调用方法,使用。"); // } //} ///// <summary> ///// 将指定的文件直接写入 HTTP 响应输出流。 ///// </summary> ///// <param name="filename">要写入 HTTP 输出流的文件名。</param> ///// <param name="offset">文件中将开始进行写入的字节位置。</param> ///// <param name="size">要写入输出流的字节数。</param> ///// <exception cref="System.Web.HttpException">offset 小于 0。 - 或 - size 大于文件大小减去 offset。</exception> ///// <exception cref="System.ArgumentNullException">filename 参数为 null。</exception> //public void WriteFile(string filename, long offset, long size) //{ // if (Response != null) // { // Response.WriteFile(filename, offset, size); // } // else // { // throw new System.Exception("请在{Ashx注入后}调用方法,使用。"); // } //} ///// <summary> ///// 将指定的文件直接写入 HTTP 响应输出流。 ///// </summary> ///// <param name="fileHandle">要写入 HTTP 输出流的文件的文件句柄。</param> ///// <param name="offset">文件中将开始进行写入的字节位置。</param> ///// <param name="size">要写入输出流的字节数。</param> ///// <exception cref="System.ArgumentNullException">fileHandler 为 null。</exception> ///// <exception cref="System.Web.HttpException">offset 小于 0。 - 或 - size 大于文件大小减去 offset。</exception> //public void WriteFile(IntPtr fileHandle, long offset, long size) //{ // if (Response != null) // { // Response.WriteFile(fileHandle, offset, size); // } // else // { // throw new System.Exception("请在{Ashx注入后}调用方法,使用。"); // } //} void IHttpApi.SetRouteData(AshxRouteData ashxRoute) { this.routeData = ashxRoute; //this.context = routeData.HttpContext; //this.session = context.Session; //this.request = context.Request; //this.response = context.Response; }
/// <summary> /// 实现JSON格式的输出 /// </summary> /// <param name="ashxRoute">当前请求对象</param> /// <returns></returns> public override async Task ExecuteOutAsync(AshxRouteData ashxRoute) { string json; if (Data.GetType() == typeof(string)) { json = Data.ToString(); } else { json = Data.ToJson(JsonOptions ?? ashxRoute.JsonOptions); } byte[] bytes = json.ToBytes(Encoding.UTF8); await ashxRoute.HttpContext.Response.WriteAsync(bytes); }
private static async Task IsTaskException(AshxException ex, AshxRouteData ashxRoute, IApiOut aipOut) { if (ex.ExceptionHandled) { if (aipOut == null) { await Task.CompletedTask; } else { await aipOut?.HttpOutput(ashxRoute);//await Task.CompletedTask; } } else { await Task.FromException(ex); } }
//public abstract void HttpOutput(AshxRouteData ashxRoute); async Task IApiOut.HttpOutput(AshxRouteData ashxRoute) { ashxRoute.HttpContext.Response.StatusCode = StatusCode; ashxRoute.HttpContext.Response.ContentType = string.Concat(ContentType, "; charset=utf-8"); await ExecuteOutAsync(ashxRoute); //HttpContext context = ashxRoute.HttpContext; //context.Response.StatusCode = StatusCode; //Microsoft.AspNetCore.Http.DefaultHttpContext ////byte[] bytes; ////string contentType; ////switch (ContentType) ////{ //// case WriteType.Html: //// contentType = "text/html"; //// //bytes = Data.ToString().ToBytes(Encoding.UTF8); //// break; //// case WriteType.Json: //// contentType = "application/json"; //// //bytes = Data.ToJson().ToBytes(Encoding.UTF8); //// break; //// case WriteType.Xml: //// contentType = "application/xml"; //// //bytes = Data.ToString().ToBytes(Encoding.UTF8); //// break; //// case WriteType.Text: //// contentType = "text/plain"; //// //bytes = Data.ToString().ToBytes(Encoding.UTF8); //// break; //// default: //// throw new Exception("出现意外输出类型!终止返回!"); ////} //string contentType = ContentType switch //{ // WriteType.Html => "text/html", // WriteType.Json => "application/json", // WriteType.Xml => "application/xml", // WriteType.Text => "text/plain", // _ => throw new Exception("出现意外输出类型!终止返回!"), //}; //context.Response.ContentType = string.Concat(contentType, ";charset=utf-8"); //await context.Response.WriteAsync(Bytes, 0, Bytes.Length); }
/// <summary> /// 获取参数 /// </summary> /// <param name="RouteData"></param> /// <param name="_objs"></param> /// <returns></returns> internal static bool GetObj(AshxRouteData RouteData, out object[] _objs) { Ashx ashx = RouteData.GetAshx; if (ashx.Parameters.Length > 0) { bool obj(out object[] _objs) { int length = ashx.Parameters.Length; _objs = new object[length]; _objs = AshxExtension.GetParameterObjs(ashx, RouteData.HttpContext.Request, 0, length, _objs, out bool isException); return(isException); } return(obj(out _objs)); } _objs = default; return(false); }
/// <summary> /// 系统回调,用于完成该请求任务的输出 /// </summary> /// <param name="ashxRoute">包含所有有效信息</param> /// <returns>异步任务</returns> public abstract Task ExecuteOutAsync(AshxRouteData ashxRoute);
/// <summary> /// 当链接真实有效时被执行,默认返回成功。(该方法是用于给使用者重写的) /// </summary> /// <param name="ashxRoute">当前请求的<see cref="AshxRouteData"/>路由,包含全部详情信息</param> /// <returns>返回输出结果,当为null的时候,表示继续执行,不为空执行输出结果。</returns> protected virtual IApiOut Initialize(AshxRouteData ashxRoute)//, out IApiOut aipOut /// <param name="aipOut">用于在返回false,输出结果的对象</param>当前请求会根据返回状态决定是否继续执行接口方法 { //aipOut = null; return(null); }
/// <summary> /// 在请求正常完成结束时触发 /// </summary> /// <param name="ashxRoute">获取接口信息</param> /// <returns></returns> protected virtual void OnResult(AshxRouteData ashxRoute) { }
protected override void OnResult(AshxRouteData ashxRoute) { //ApiOut.Redirect(""); }
/// <summary> /// 实现文本格式的输出 /// </summary> /// <param name="ashxRoute">当前请求对象</param> /// <returns></returns> public override async Task ExecuteOutAsync(AshxRouteData ashxRoute) { await ashxRoute.HttpContext.Response.WriteAsync(Text); }
/// <summary> /// 重定向核心任务函数 /// </summary> /// <param name="ashxRoute">核心传输对象</param> /// <returns>返回任务</returns> public override async Task ExecuteOutAsync(AshxRouteData ashxRoute) { ashxRoute.HttpContext.Response.Redirect(Url); await Task.CompletedTask; }
void IMinHttpApi.Request(AshxRouteData ashxRoute, object[] _objs) { Ashx ashx = ashxRoute.GetAshx; try { Func <IApiOut> func = () => { return(ashx.Action.Execute(this, _objs) as IApiOut); }; //AshxExtension.Invoke(ashx.Method, this); IApiOut aipOut = func(); aipOut?.HttpOutput(ashxRoute).Wait(); OnResult(ashxRoute); } catch (ThreadAbortException) { // This type of exception occurs as a result of Response.Redirect(), but we special-case so that // the filters don't see this as an error. throw; } catch (Exception ex) { AshxException exception = new(ashx, ex, _objs) { ExceptionHandled = true }; IApiOut aipOut = AshxException(exception); IsException(exception, ashxRoute, aipOut); } } async Task IMinHttpAsynApi.TaskRequest(AshxRouteData ashxRoute, object[] _objs) { Ashx ashx = ashxRoute.GetAshx; try { //Func<Task<IApiOut>> func = () => { return ashx.Action.Execute(this, _objs) as Task<IApiOut>; }; //IApiOut aipOut = await func(); //System.Runtime.CompilerServices.AsyncTaskMethodBuilder //System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> asyncTaskMethodBuilder = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create(); //Task task = func(); //AsyncStateMachineBox //Utils.Data.DictionaryExtension.ToDictionary(task); //Type type = task.GetType(); //var field = type.GetType().GetField("Result", System.Reflection.BindingFlags.Public); async Task <IApiOut> func() => await(Task <IApiOut>) ashx.Action.Execute(this, _objs); //{ // return await (Task<IApiOut>)ashx.Action.Execute(this, _objs); // //Task <IApiOut> task = ashx.Action.Execute(this, _objs) as Task<IApiOut>; // //return await task; //} //Task //object _task = func();// dynamic,Task //Task.WaitAll<object>((func() as Task<object>)); //for (int i = 0; i < 1000000; i++) //{ // IApiOut aipOut1 = _task.GetValue("Result") as IApiOut; //aipOut1.Result as IApiOut; //} //var _r = _task.GetPropertieFind("Result"); //for (int i = 0; i < 1000000; i++) //{ // IApiOut aipOut1 = _task.GetValue(_r) as IApiOut; //aipOut1.Result as IApiOut; //} //Task<object> s = Task.FromResult<object>(100); //for (int i = 0; i < 100000000; i++) //{ // object aipOut1 = s.Result; //aipOut1.Result as IApiOut; //} //dynamic d = _task; //for (int i = 0; i < 100000000; i++) //{ // IApiOut aipOut1 = d.Result; //aipOut1.Result as IApiOut; //} IApiOut aipOut = await func();//_task.GetValue("Result") as IApiOut; //aipOut1.Result as IApiOut; await aipOut?.HttpOutput(ashxRoute); OnResult(ashxRoute); } //catch (ThreadAbortException ex) //{ // // This type of exception occurs as a result of Response.Redirect(), but we special-case so that // // the filters don't see this as an error. // throw; //} //catch (AshxException ex) //{ // AshxException(new AshxException(ashx, ex) { ExceptionHandled = true }); //} catch (Exception ex) { //AshxException(new AshxException(ashx, ex) { ExceptionHandled = true }); AshxException exception = new(ashx, ex, _objs) { ExceptionHandled = true }; IApiOut aipOut = AshxException(exception); await IsTaskException(exception, ashxRoute, aipOut); } //return await Task<IAipOut>.FromResult<IAipOut>(default); } void IMinHttpAsynApi.ContinueWith(Task task, AshxRouteData ashxRoute) { if (task.IsFaulted) { if (task.Exception.GetBaseException() is AshxException ashxException && !ashxException.ExceptionHandled) { throw ashxException; } //AshxException ashxException = task.Exception.GetBaseException() as AshxException; //if (ashxException != null && !ashxException.ExceptionHandled) throw ashxException; //AshxException(new AshxException(ashxRoute.GetAshx, new Exception("发生异常,异步处理过程中发生异常。", task.Exception.GetBaseException())) { ExceptionHandled = true }); } else if (!task.IsCompleted) { throw new Exception("发生异常,异步处理未完成。"); //AshxException(new AshxException(ashxRoute.GetAshx, ) { ExceptionHandled = true }); } //else //{ // IAipOut aipOut = task.Result; // aipOut?.HttpOutput(ashxRoute.HttpContext).Wait(); //} } }
/// <summary> /// 实现页面内容的输出(采用异步IO读取) /// </summary> /// <param name="ashxRoute">当前请求对象</param> /// <returns></returns> public override async Task ExecuteOutAsync(AshxRouteData ashxRoute) { Microsoft.AspNetCore.Hosting.IWebHostEnvironment env = ashxRoute.HttpContext.GetService <Microsoft.AspNetCore.Hosting.IWebHostEnvironment>(); Microsoft.Extensions.FileProviders.IFileInfo view; if (env.WebRootPath is null) { string webRootPath = env.ContentRootPath + "\\wwwroot"; System.IO.Directory.CreateDirectory(webRootPath + "\\Views"); env.WebRootPath = webRootPath; env.WebRootFileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(webRootPath); } //string filePath = ""; if (IsView) { //string directory = AppContext.BaseDirectory; //filePath = string.Concat(directory, "ApiView\\", ashxRoute.Controller, '\\', ashxRoute.Action, ".html"); if (string.IsNullOrEmpty(ViewName)) { ViewName = $"Views\\{ashxRoute.Controller}\\{ashxRoute.Action}.html"; } else { ViewName = $"Views\\{ashxRoute.Controller}\\{ViewName}\\{ashxRoute.Action}.html"; } view = env.WebRootFileProvider.GetFileInfo(ViewName); } else { view = env.WebRootFileProvider.GetFileInfo(ViewName); //if (ViewName != null && ViewName[1].Equals(':')) //{ // filePath = ViewName; //} //else //{ // string directory = AppContext.BaseDirectory; // filePath = string.Concat(directory, ViewName);// '\\' $"{directory}/{ViewName}"; //} //System.IO.File.Exists(@"D:\Nixue工作室\Tool.Net\WebTestApp\wwwroot\"+ViewName); //System.IO.File.OpenRead(@"D:\Nixue工作室\Tool.Net\WebTestApp\wwwroot\" + ViewName); } //if (System.IO.File.Exists(filePath)) //{ // filePath = viewName; //} //else //{ // string directory = AppContext.BaseDirectory.Replace("\\", "/"); // filePath = $"{directory}/{viewName}"; //} if (view.Exists) { //byte[] obj = System.IO.File.ReadAllBytes(filePath); //byte[] obj = await System.IO.File.ReadAllBytesAsync(filePath); //await ashxRoute.HttpContext.Response.WriteAsync(obj); System.IO.Stream streamview = view.CreateReadStream(); System.IO.Stream writeStream = ashxRoute.HttpContext.Response.Body; //long len = (1024 * 50) > view.Length ? view.Length : (1024 * 50); //byte[] slice = new byte[len]; //long seekiength = 0; //do //{ // int i = await streamview.ReadAsync(slice.AsMemory(0, slice.Length)); // await writeStream.WriteAsync(slice.AsMemory(0, i)); // await writeStream.FlushAsync(); // seekiength += i; // Array.Clear(slice, 0, i); //} while (view.Length > seekiength); //await streamview.DisposeAsync(); await HttpContextExtension.StreamMove(streamview, writeStream, 1024 * 50); } else { throw new Exception("找不到页面:“(相对路径)wwwroot\\" + ViewName + "”,无法显示!"); } }