//处理客户端请求 private void HandleRequest(object ctx) { HttpListenerContext context = ctx as HttpListenerContext; HttpListenerResponse response = context.Response; HttpListenerRequest request = context.Request; //返回数据构建 EditorHttpResonseData retdata = null; try { //格式化url string rawUrl = Uri.UnescapeDataString(request.RawUrl); int paramStartIndex = rawUrl.IndexOf('?'); if (paramStartIndex > 0) { rawUrl = rawUrl.Substring(0, paramStartIndex); } else if (paramStartIndex == 0) { rawUrl = ""; } if (rawUrl.StartsWith("/")) { rawUrl = rawUrl.Substring(1, rawUrl.Length - 1); } // rawUrl = rawUrl.Replace("//", "/"); string apiFuc = ""; string apiParams = ""; var slashIdx = rawUrl.IndexOf("/"); if (slashIdx > 0) { apiFuc = rawUrl.Substring(0, slashIdx); apiParams = rawUrl.Substring(slashIdx + 1); } else { //只有参数,没有协议 apiParams = rawUrl; } //调用proccesor retdata = InvokeProccessor(apiFuc, apiParams, response); } catch (Exception ex) { retdata = new EditorHttpResonseData(); retdata.err = true; retdata.content = ex.Message; } //填充返回数据 if (request != null) { //返回 if (retdata.err) { response.StatusCode = 400; } else { response.StatusCode = 200; } //返回类型 response.ContentType = "text/json"; using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { var json = JsonMapper.ToJson(retdata); writer.WriteLine(json); } } //关闭response try { response.Close(); } catch (Exception ex) { Debug.LogError(ex); } }
/// <summary> /// webapi处理器 /// </summary> /// <param name="apiParams"></param> /// <param name="response"></param> /// <exception cref="Exception"></exception> async public Task <EditorHttpResonseData> WebAPIProccessor(string apiParams, HttpListenerResponse response) { var ret = functionCacheMap.TryGetValue(apiParams, out var methodInfo); if (!ret) { var lastDotIdx = apiParams.LastIndexOf("."); if (lastDotIdx == -1) { throw new Exception("Function不存在"); } var clasname = apiParams.Substring(0, lastDotIdx); var funcname = apiParams.Substring(lastDotIdx + 1); //获取type var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type type = null; foreach (var assembly in assemblies) { type = assembly.GetTypes().FirstOrDefault((t) => t.FullName.Equals(clasname, StringComparison.OrdinalIgnoreCase)); if (type != null) { break; } } // if (type != null) { methodInfo = type.GetMethod(funcname, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (methodInfo != null) { functionCacheMap[apiParams] = methodInfo; } else { throw new Exception("Function不存在"); } } else { throw new Exception("ClassType不存在"); } } try { await UniTask.SwitchToMainThread(); methodInfo.Invoke(null, null); } catch (Exception e) { var err = e.ToString(); Debug.LogError(e); if (e.InnerException != null) { err += ("\n" + e.InnerException.ToString()); Debug.LogError(e.InnerException); } throw new Exception("Function 执行报错,请查看Unity! \n" + err); } var retdata = new EditorHttpResonseData(); retdata.content = "执行成功"; response.StatusCode = 200; return(retdata); }