Пример #1
0
        private async Task ProcessHttpRequestAsync(HttpListenerContext context)
        {
            try
            {
                var request  = context.Request;
                var response = context.Response;

                response.ContentEncoding = Encoding.UTF8;
                response.ContentType     = "text/html;charset=utf-8";

                //TODO ***通过request来的值进行接口调用

                //getJson
                var json = GetClientsInfoJson();
                await response.OutputStream.WriteAsync(HtmlUtil.GetContent(json.ToString()));

                //await response.OutputStream.WriteAsync(HtmlUtil.GetContent(request.RawUrl));
                response.OutputStream.Close();
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                throw;
            }
        }
Пример #2
0
        private async Task ProcessHttpRequestAsync(HttpListenerContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            //TODO XX 设置该同源策略为了方便调试,真实项目请确保同源

#if DEBUG
            response.AddHeader("Access-Control-Allow-Origin", "*");
#endif
            response.Headers["Server"] = "";
            try
            {
                //通过request来的值进行接口调用
                string unit = request.RawUrl.Replace("//", "");

                if (unit == "/")
                {
                    unit = INDEX_PAGE;
                }

                int idx1 = unit.LastIndexOf("#");
                if (idx1 > 0)
                {
                    unit = unit.Substring(0, idx1);
                }
                int idx2 = unit.LastIndexOf("?");
                if (idx2 > 0)
                {
                    unit = unit.Substring(0, idx2);
                }
                int idx3 = unit.LastIndexOf(".");

                //通过后缀获取不同的文件,若无后缀,则调用接口
                if (idx3 > 0)
                {
                    if (!File.Exists(BASE_FILE_PATH + unit))
                    {
                        Logger.Debug($"未找到文件{BASE_FILE_PATH + unit}");
                        return;
                    }
                    //mime类型
                    ProcessMIME(response, unit.Substring(idx3));
                    //TODO 权限控制(只是控制html权限而已)

                    //读文件优先去缓存读
                    if (FilesCache.TryGetValue(unit.TrimStart('/'), out MemoryStream memoryStream))
                    {
                        memoryStream.Position = 0;
                        await memoryStream.CopyToAsync(response.OutputStream);
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(BASE_FILE_PATH + unit, FileMode.Open))
                        {
                            await fs.CopyToAsync(response.OutputStream);
                        }
                    }
                }
                else  //url中没有小数点则是接口
                {
                    unit = unit.Replace("/", "");
                    response.ContentEncoding = Encoding.UTF8;

                    //调用接口 用分布类隔离并且用API特性限定安全
                    object jsonObj;
                    //List<string> qsStrList;
                    int      qsCount    = request.QueryString.Count;
                    object[] parameters = null;
                    if (qsCount > 0)
                    {
                        parameters = new object[request.QueryString.Count];
                        for (int i = 0; i < request.QueryString.Count; i++)
                        {
                            parameters[i] = request.QueryString[i];
                        }
                    }

                    //反射调用API方法
                    MethodInfo method = null;
                    try
                    {
                        method = ControllerInstance.GetType().GetMethod(unit);
                        if (method == null)
                        {
                            //Server.Logger.Debug($"无效的方法名{unit}");
                            throw new Exception($"无效的方法名{unit}");
                        }

                        //debug编译时不校验,方便调试
#if !DEBUG
                        if (method.GetCustomAttribute <SecureAttribute>() != null)
                        {
                            if (request.Cookies["NSPTK"] == null)
                            {
                                throw new Exception("用户未登录。");
                            }
                            //TODO cookie,根据不同的用户角色分配权限。
                            var UserClaims = StringUtil.ConvertStringToTokenClaims(request.Cookies["NSPTK"].Value);
                            if (string.IsNullOrEmpty(UserClaims.UserKey))
                            {
                                throw new Exception("登录信息异常。");
                            }
                        }
#endif

                        if (method.GetCustomAttribute <APIAttribute>() != null)
                        {
                            //返回json,类似WebAPI
                            response.ContentType = "application/json";
                            jsonObj = method.Invoke(ControllerInstance, parameters);
                            await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));
                        }
                        else if (method.GetCustomAttribute <FormAPIAttribute>() != null)
                        {
                            //返回表单页面
                            response.ContentType = "text/html";
                            jsonObj = method.Invoke(ControllerInstance, parameters);
                            await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.ToString()));
                        }
                        else if (method.GetCustomAttribute <ValidateAPIAttribute>() != null)
                        {
                            //验证模式
                            response.ContentType = "application/json";
                            bool validateResult = (bool)method.Invoke(ControllerInstance, parameters);
                            if (validateResult == true)
                            {
                                await response.OutputStream.WriteAsync(HtmlUtil.GetContent("{\"valid\":true}"));
                            }
                            else
                            {
                                await response.OutputStream.WriteAsync(HtmlUtil.GetContent("{\"valid\":false}"));
                            }
                        }
                        else if (method.GetCustomAttribute <FileAPIAttribute>() != null)
                        {
                            //文件下载
                            response.ContentType = "application/octet-stream";
                            if (!(method.Invoke(ControllerInstance, parameters) is FileDTO fileDto))
                            {
                                throw new Exception("文件返回失败,请查看错误日志。");
                            }

                            response.Headers.Add("Content-Disposition", "attachment;filename=" + fileDto.FileName);
                            //response.OutputStream.(stream);
                            using (fileDto.FileStream)
                            {
                                await fileDto.FileStream.CopyToAsync(response.OutputStream);
                            }
                        }
                        else if (method.GetCustomAttribute <FileUploadAttribute>() != null)
                        {
                            //文件上传
                            response.ContentType = "application/json";
                            if (request.HttpMethod.ToUpper() == "POST")
                            {
                                List <object> paraList = new List <object>();
                                var           fileName = SaveFile(request.ContentEncoding, request.ContentType, request.InputStream);
                                paraList.Add(new FileInfo($"./{fileName}"));
                                if (parameters != null)
                                {
                                    paraList.AddRange(parameters);
                                }
                                jsonObj = method.Invoke(ControllerInstance, paraList.ToArray());
                                await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));
                            }
                            else
                            {
                                await response.OutputStream.WriteAsync(HtmlUtil.GetContent(HttpResult <object> .NullSuccessResult.ToJsonString()));
                            }


                            //request.
                        }
                    }
                    catch (Exception ex)
                    {
                        if ((ex is TargetInvocationException) && ex.InnerException != null)
                        {
                            ex = ex.InnerException;
                        }
                        Logger.Error(ex.Message, ex);
                        jsonObj = new Exception(ex.Message + "---" + ex.StackTrace);
                        response.ContentType = "application/json";
                        await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));
                    }
                    finally
                    {
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                throw;
            }
            finally
            {
                response.OutputStream.Close();
            }
        }
Пример #3
0
        private async Task ProcessHttpRequestAsync(HttpListenerContext context)
        {
            string baseFilePath = "./Extension/HttpServerStaticFiles/";
            var    request      = context.Request;
            var    response     = context.Response;

            //TODO XX 设置该同源策略为了方便调试,请确保web项目也位于locahost5671上
            response.AddHeader("Access-Control-Allow-Origin", "http://localhost:5671");

            try
            {
                //TODO ***通过request来的值进行接口调用
                string unit = request.RawUrl.Replace("//", "");
                int    idx1 = unit.LastIndexOf("#");
                if (idx1 > 0)
                {
                    unit = unit.Substring(0, idx1);
                }
                int idx2 = unit.LastIndexOf("?");
                if (idx2 > 0)
                {
                    unit = unit.Substring(0, idx2);
                }
                int idx3 = unit.LastIndexOf(".");

                //TODO 通过后缀获取不同的文件,若无后缀,则调用接口
                if (idx3 > 0)
                {
                    if (!File.Exists(baseFilePath + unit))
                    {
                        Server.Logger.Debug($"未找到文件{baseFilePath + unit}");
                        return;
                    }
                    //mime类型
                    ProcessMIME(response, unit.Substring(idx3));
                    using (FileStream fs = new FileStream(baseFilePath + unit, FileMode.Open))
                    {
                        await fs.CopyToAsync(response.OutputStream);
                    }
                }
                else
                {
                    unit = unit.Replace("/", "");
                    response.ContentEncoding = Encoding.UTF8;
                    response.ContentType     = "application/json";

                    //TODO XXXXXX 调用接口 接下来要用分布类隔离并且用API特性限定安全
                    object jsonObj;
                    //List<string> qsStrList;
                    int      qsCount    = request.QueryString.Count;
                    object[] parameters = null;
                    if (qsCount > 0)
                    {
                        parameters = new object[request.QueryString.Count];
                        for (int i = 0; i < request.QueryString.Count; i++)
                        {
                            parameters[i] = request.QueryString[i];
                        }
                    }

                    // request.QueryString[0]
                    try
                    {
                        jsonObj = this.GetType().GetMethod(unit).Invoke(this, parameters);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e.Message, e);
                        jsonObj = e.Message + "---" + e.StackTrace;
                    }

                    //getJson
                    //var json = GetClientsInfoJson();
                    //无返回值则返回默认数据。
                    //if (jsonObj == null) await response.OutputStream.WriteAsync(HtmlUtil.GetContent(""));
                    await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));

                    //await response.OutputStream.WriteAsync(HtmlUtil.GetContent(request.RawUrl));
                    // response.OutputStream.Close();
                }
                //suffix = unit.Substring(unit.LastIndexOf(".")+1,)
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                throw;
            }
            finally
            {
                response.OutputStream.Close();
            }
        }
Пример #4
0
        private async Task ProcessHttpRequestAsync(HttpListenerContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            //TODO XX 设置该同源策略为了方便调试,请确保web项目也位于locahost5671上

#if DEBUG
            response.AddHeader("Access-Control-Allow-Origin", "*");
#endif

            try
            {
                //TODO ***通过request来的值进行接口调用
                string unit = request.RawUrl.Replace("//", "");

                if (unit == "/")
                {
                    unit = INDEX_PAGE;
                }

                int idx1 = unit.LastIndexOf("#");
                if (idx1 > 0)
                {
                    unit = unit.Substring(0, idx1);
                }
                int idx2 = unit.LastIndexOf("?");
                if (idx2 > 0)
                {
                    unit = unit.Substring(0, idx2);
                }
                int idx3 = unit.LastIndexOf(".");

                //TODO 通过后缀获取不同的文件,若无后缀,则调用接口
                if (idx3 > 0)
                {
                    if (!File.Exists(BASE_FILE_PATH + unit))
                    {
                        Server.Logger.Debug($"未找到文件{BASE_FILE_PATH + unit}");
                        return;
                    }
                    //mime类型
                    ProcessMIME(response, unit.Substring(idx3));

                    //读文件优先去缓存读
                    MemoryStream memoryStream;
                    if (FilesCache.TryGetValue(unit.TrimStart('/'), out memoryStream))
                    {
                        memoryStream.Position = 0;
                        await memoryStream.CopyToAsync(response.OutputStream);
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(BASE_FILE_PATH + unit, FileMode.Open))
                        {
                            await fs.CopyToAsync(response.OutputStream);
                        }
                    }
                }
                else
                {
                    unit = unit.Replace("/", "");
                    response.ContentEncoding = Encoding.UTF8;


                    //TODO XXXXXX 调用接口 接下来要用分布类隔离并且用API特性限定安全
                    object jsonObj;
                    //List<string> qsStrList;
                    int      qsCount    = request.QueryString.Count;
                    object[] parameters = null;
                    if (qsCount > 0)
                    {
                        parameters = new object[request.QueryString.Count];
                        for (int i = 0; i < request.QueryString.Count; i++)
                        {
                            parameters[i] = request.QueryString[i];
                        }
                    }

                    // request.QueryString[0]
                    MethodInfo method = null;
                    try
                    {
                        method = this.GetType().GetMethod(unit);
                        if (method == null)
                        {
                            Server.Logger.Debug($"无效的方法名{unit}");
                        }

                        if (method.GetCustomAttribute <APIAttribute>() != null)
                        {
                            response.ContentType = "application/json";
                            jsonObj = method.Invoke(this, parameters);
                            await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));
                        }
                        else if (method.GetCustomAttribute <FormAPIAttribute>() != null)
                        {
                            response.ContentType = "text/html";
                            jsonObj = method.Invoke(this, parameters);
                            await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.ToString()));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex.Message, ex);
                        jsonObj = new Exception(ex.Message + "---" + ex.StackTrace);
                        response.ContentType = "application/json";
                        await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));
                    }
                }
                //suffix = unit.Substring(unit.LastIndexOf(".")+1,)
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                throw;
            }
            finally
            {
                response.OutputStream.Close();
            }
        }
Пример #5
0
        private async Task ProcessHttpRequestAsync(HttpListenerContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            //TODO XX 设置该同源策略为了方便调试,请确保web项目也位于locahost5671上

#if DEBUG
            response.AddHeader("Access-Control-Allow-Origin", "*");
#endif

            try
            {
                //通过request来的值进行接口调用
                string unit = request.RawUrl.Replace("//", "");

                if (unit == "/")
                {
                    unit = INDEX_PAGE;
                }

                int idx1 = unit.LastIndexOf("#");
                if (idx1 > 0)
                {
                    unit = unit.Substring(0, idx1);
                }
                int idx2 = unit.LastIndexOf("?");
                if (idx2 > 0)
                {
                    unit = unit.Substring(0, idx2);
                }
                int idx3 = unit.LastIndexOf(".");

                //TODO 通过后缀获取不同的文件,若无后缀,则调用接口
                if (idx3 > 0)
                {
                    if (!File.Exists(BASE_FILE_PATH + unit))
                    {
                        Server.Logger.Debug($"未找到文件{BASE_FILE_PATH + unit}");
                        return;
                    }
                    //mime类型
                    ProcessMIME(response, unit.Substring(idx3));
                    //TODO 权限控制(只是控制html权限而已)


                    //读文件优先去缓存读
                    MemoryStream memoryStream;
                    if (FilesCache.TryGetValue(unit.TrimStart('/'), out memoryStream))
                    {
                        memoryStream.Position = 0;
                        await memoryStream.CopyToAsync(response.OutputStream);
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(BASE_FILE_PATH + unit, FileMode.Open))
                        {
                            await fs.CopyToAsync(response.OutputStream);
                        }
                    }
                }
                else  //url中没有小数点则是接口
                {
                    unit = unit.Replace("/", "");
                    response.ContentEncoding = Encoding.UTF8;

                    //调用接口 用分布类隔离并且用API特性限定安全
                    object jsonObj;
                    //List<string> qsStrList;
                    int      qsCount    = request.QueryString.Count;
                    object[] parameters = null;
                    if (qsCount > 0)
                    {
                        parameters = new object[request.QueryString.Count];
                        for (int i = 0; i < request.QueryString.Count; i++)
                        {
                            parameters[i] = request.QueryString[i];
                        }
                    }

                    //反射调用API方法
                    MethodInfo method = null;
                    try
                    {
                        method = this.GetType().GetMethod(unit);
                        if (method == null)
                        {
                            //Server.Logger.Debug($"无效的方法名{unit}");
                            throw new Exception($"无效的方法名{unit}");
                        }

                        //TODO 先不校验,方便调试
                        //if (method.GetCustomAttribute<SecureAttribute>() != null)
                        //{
                        //    if (request.Cookies["NSPTK"] == null)
                        //        throw new Exception("用户未登陆。");
                        //    //TODO cookie,根据不同的用户角色分配权限。
                        //    var UserClaims = StringUtil.ConvertStringToTokenClaims(request.Cookies["NSPTK"].Value);
                        //    if (string.IsNullOrEmpty(UserClaims.UserKey))
                        //    {
                        //        throw new Exception("登陆信息异常。");
                        //    }
                        //}

                        if (method.GetCustomAttribute <APIAttribute>() != null)
                        {
                            response.ContentType = "application/json";
                            jsonObj = method.Invoke(this, parameters);
                            await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));
                        }
                        else if (method.GetCustomAttribute <FormAPIAttribute>() != null)
                        {
                            response.ContentType = "text/html";
                            jsonObj = method.Invoke(this, parameters);
                            await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.ToString()));
                        }
                        else if (method.GetCustomAttribute <ValidateAPIAttribute>() != null)
                        {
                            response.ContentType = "application/json";
                            bool validateResult = (bool)method.Invoke(this, parameters);
                            if (validateResult == true)
                            {
                                await response.OutputStream.WriteAsync(HtmlUtil.GetContent("{\"valid\":true}"));
                            }
                            else
                            {
                                await response.OutputStream.WriteAsync(HtmlUtil.GetContent("{\"valid\":false}"));
                            }
                        }
                        else if (method.GetCustomAttribute <FileAPIAttribute>() != null)
                        {
                            response.ContentType = "application/octet-stream";
                            FileDTO fileDto = method.Invoke(this, parameters) as FileDTO;
                            if (fileDto == null)
                            {
                                throw new Exception("文件返回失败,请查看错误日志。");
                            }

                            response.Headers.Add("Content-Disposition", "attachment;filename=" + fileDto.FileName);
                            //response.OutputStream.(stream);
                            using (fileDto.FileStream)
                            {
                                await fileDto.FileStream.CopyToAsync(response.OutputStream);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex.Message, ex);
                        jsonObj = new Exception(ex.Message + "---" + ex.StackTrace);
                        response.ContentType = "application/json";
                        await response.OutputStream.WriteAsync(HtmlUtil.GetContent(jsonObj.Wrap().ToJsonString()));
                    }
                    finally
                    {
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                throw;
            }
            finally
            {
                response.OutputStream.Close();
            }
        }