public static Exploit ParseExploit(int id) { Exploit exploit = new Exploit(id); HttpManager http = new HttpManager(Encoding.UTF8, UserAgents.GoogleBot21); http.RequestGET(exploit.Link); if (http.Result.Contains("")) { return null; } exploit.Title = http.Result.GetStringBetween("").Replace("| Inj3ct0r - exploit database : vulnerability : 0day : shellcode", string.Empty).HTMLDecodeSpecialChars().Trim(); exploit.Content = http.Result.GetStringBetween(openPreTag.HTMLDecodeSpecialChars(), closePreTag.HTMLDecodeSpecialChars()).Replace(openATag.HTMLDecodeSpecialChars() + " href='http://www.1337day.com/'>1337day.com", "1337day.com").HTMLDecodeSpecialChars().Trim(); exploit.Date = http.Result.GetStringBetween("# " + openATag.HTMLDecodeSpecialChars() + " href='http://www.1337day.com/'>1337day.com [", "]" + closePreTag.HTMLDecodeSpecialChars()).Trim(); return exploit; }
public static Promise <FetchSearchArticleResponse> SearchArticle(string keyword, int pageNumber) { var promise = new Promise <FetchSearchArticleResponse>(); var para = new Dictionary <string, object> { { "t", "project" }, { "projectType", "article" }, { "k", $"[\"q:{keyword}\"]" }, { "searchAllLoadMore", "false" }, { "page", pageNumber } }; var request = HttpManager.GET($"{Config.apiAddress}/api/search", para); HttpManager.resume(request).Then(responseText => { var searchResponse = JsonConvert.DeserializeObject <FetchSearchArticleResponse>(responseText); promise.Resolve(searchResponse); }).Catch(exception => promise.Reject(exception)); return(promise); }
public static IPromise <FetchEventsResponse> FetchEvents(int pageNumber, string tab, string mode = "") { var promise = new Promise <FetchEventsResponse>(); var para = new Dictionary <string, object> { { "tab", tab }, { "page", pageNumber }, { "status", tab }, { "language", "zh_CN" }, { "mode", mode } }; var request = HttpManager.GET($"{Config.apiAddress}{Config.apiPath}/events", parameter: para); HttpManager.resume(request: request).Then(responseText => { var eventsResponse = JsonConvert.DeserializeObject <FetchEventsResponse>(value: responseText); promise.Resolve(value: eventsResponse); }).Catch(exception => promise.Reject(ex: exception)); return(promise); }
public void GetJsonBody() { using (HttpManager.OverrideContext("/?a=xxx&b=1", "POST")) { var request = HttpManager.CurrentContext.Request; Assert.Equals(request.GetJsonBody(), null); } using (HttpManager.OverrideContext("", "POST")) { var request = (HttpRequestMock)HttpManager.CurrentContext.Request; var json = "{ a: 'xxx', b: 1 }"; request.contentType = "application/json"; request.body = new MemoryStream(Encoding.UTF8.GetBytes(json)); Assert.Equals(request.GetJsonBody(), json); Assert.Equals(request.GetJsonBody(), json); // repeat } }
public void OnRequestTest_D_JsonBody() { OnRequestTest(() => { // test get complex parameter from json body var controllerManager = Application.Ioc.Resolve<ControllerManager>(); using (HttpManager.OverrideContext("__test_action_d", HttpMethods.POST)) { var request = (HttpRequestMock)HttpManager.CurrentContext.Request; request.contentType = "application/json"; request.body = new MemoryStream(Encoding.UTF8.GetBytes("{ param: { name: 'john', age: 50 } }")); var response = (HttpResponseMock)HttpManager.CurrentContext.Response; controllerManager.OnRequest(); Assert.Equals(response.ContentType, "application/json; charset=utf-8"); var json = response.GetContentsFromBody(); var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>(json); Assert.Equals(obj.GetOrDefault<string>("name"), "john"); Assert.Equals(obj.GetOrDefault<int>("age"), 50); } }); }
#pragma warning disable CS0618 public void WriteFile() { using (HttpManager.OverrideContext("", "POST")) { var path = Path.GetTempFileName(); File.WriteAllText(path, "test file contents"); try { var response = (HttpResponseMock)HttpManager.CurrentContext.Response; response.WriteFile(path); Assert.Equals(response.GetContentsFromBody(), "test file contents"); } finally { File.Delete(path); } } }
public static IPromise <LoginInfo> LoginByWechat(string code) { var promise = new Promise <LoginInfo>(); var para = new WechatLoginParameter { code = code }; var body = JsonConvert.SerializeObject(para); var request = HttpManager.initRequest(Config.apiAddress + "/auth/live/wechat", Method.POST); var bodyRaw = Encoding.UTF8.GetBytes(body); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.SetRequestHeader("Content-Type", "application/json"); HttpManager.resume(request).Then(responseText => { var loginInfo = JsonConvert.DeserializeObject <LoginInfo>(responseText); promise.Resolve(loginInfo); }).Catch(exception => { promise.Reject(exception); }); return(promise); }
public static object removeLikeComment(Message message) { if (HttpManager.isNetWorkError()) { CustomDialogUtils.showToast("请检查网络", iconData: Icons.sentiment_dissatisfied); return(null); } return(new ThunkAction <AppState>((dispatcher, getState) => { CustomDialogUtils.showToast("已取消点赞", iconData: Icons.sentiment_satisfied); dispatcher.dispatch(new RemoveLikeCommentSuccessAction { message = message }); return ArticleApi.RemoveLikeComment(commentId: message.id) .Then(mess => { }) .Catch(error => { }); })); }
public static object likeArticle(string articleId, int addCount = 1) { if (HttpManager.isNetWorkError()) { CustomDialogUtils.showToast("请检查网络", iconData: Icons.sentiment_dissatisfied); return(null); } return(new ThunkAction <AppState>((dispatcher, getState) => { dispatcher.dispatch(new LikeArticleSuccessAction { articleId = articleId, likeCount = addCount }); return ArticleApi.LikeArticle(articleId: articleId, addCount: addCount) .Then(() => { }) .Catch(_ => { }); })); }
public static Promise <FetchArticlesResponse> FetchArticles(int offset) { var promise = new Promise <FetchArticlesResponse>(); var para = new Dictionary <string, object> { { "language", "zh_CN" }, { "hottestHasMore", "true" }, { "feedHasMore", "false" }, { "isApp", "true" }, { "hottestOffset", offset } }; var request = HttpManager.GET($"{Config.apiAddress}/api/getFeedList", parameter: para); HttpManager.resume(request).Then(responseText => { var articlesResponse = JsonConvert.DeserializeObject <FetchArticlesResponse>(responseText); promise.Resolve(articlesResponse); }).Catch(exception => { promise.Reject(exception); }); return(promise); }
public static object joinChannel(string channelId, string groupId = null, bool loading = false) { if (HttpManager.isNetWorkError()) { CustomDialogUtils.showToast("请检查网络", iconData: Icons.sentiment_dissatisfied); return(null); } if (loading) { CustomDialogUtils.showCustomDialog(child: new CustomLoadingDialog(message: "正在加入群聊")); } return(new ThunkAction <AppState>((dispatcher, getState) => { return ChannelApi.JoinChannel(channelId: channelId, groupId: groupId) .Then(joinChannelResponse => { if (loading) { CustomDialogUtils.hiddenCustomDialog(); } dispatcher.dispatch(new JoinChannelSuccessAction { channelId = channelId, member = joinChannelResponse.member }); dispatcher.dispatch(fetchChannelMessages(channelId: channelId)); dispatcher.dispatch(new FetchChannelMemberSuccessAction { channelId = channelId, member = joinChannelResponse.member }); }) .Catch(error => { if (loading) { CustomDialogUtils.hiddenCustomDialog(); } dispatcher.dispatch(new JoinChannelFailureAction { channelId = channelId }); Debuger.LogError(message: error); }); })); }
/// <summary> /// [异步async]下载文件到本地 /// </summary> /// <param name="url">(可访问的或者已授权的)链接</param> /// <param name="saveasFile">(另存为)本地文件名</param> /// <returns>下载资源的结果</returns> public static async Task <HttpResult> DownloadAsync(string url, string saveasFile) { HttpResult result = new HttpResult(); try { HttpManager httpManager = new HttpManager(); result = await httpManager.GetAsync(url, null, true); if (result.Code == (int)HttpCode.OK) { using (FileStream fs = File.Create(saveasFile, result.Data.Length)) { fs.Write(result.Data, 0, result.Data.Length); fs.Flush(); } result.RefText += string.Format("[{0}] [Download] Success: (Remote file) ==> \"{1}\"\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), saveasFile); } else { result.RefText += string.Format("[{0}] [Download] Error: code = {1}\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), result.Code); } } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("[{0}] Download Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); Exception e = ex; while (e != null) { sb.Append(e.Message + " "); e = e.InnerException; } sb.AppendLine(); result.RefCode = (int)HttpCode.USER_EXCEPTION; result.RefText += sb.ToString(); } return(result); }
public ResumeUploader(ResumeRecorder recorder, string recordKey, Stream stream, string key, string token, UploadOptions uploadOptions, UpCompletionHandler upCompletionHandler) { this.mHttpManager = new HttpManager(); this.resumeRecorder = recorder; this.recordKey = recordKey; this.fileStream = stream; this.key = key; this.uploadOptions = (uploadOptions == null) ? UploadOptions.defaultOptions() : uploadOptions; this.upCompletionHandler = new UpCompletionHandler(delegate(string fileKey, ResponseInfo respInfo, string response) { if (respInfo.isOk()) { this.uploadOptions.ProgressHandler(key, 1.0); } if (this.fileStream != null) { try { this.fileStream.Close(); this.fileStream = null; } catch (Exception) { } } try { if (upCompletionHandler != null) { upCompletionHandler(key, respInfo, response); } } catch (Exception ex) { Console.WriteLine("resumable upload completion error, {0}", ex.Message); } }); string upTokenHeader = string.Format("UpToken {0}", token); this.upHeaders = new Dictionary <string, string>(); this.upHeaders.Add("Authorization", upTokenHeader); this.chunkBuffer = new byte[Config.CHUNK_SIZE]; }
/// <summary> /// 下载文件到本地 /// </summary> /// <param name="url">(可访问的或者已授权的)链接</param> /// <param name="saveasFile">(另存为)本地文件名</param> /// <returns>下载资源的结果</returns> public async Task <HttpResult> Download(string url, string saveasFile) { var result = new HttpResult(); try { var httpManager = new HttpManager(); result = await httpManager.GetAsync(url, null, true); if (result.Code == (int)HttpCode.OK) { using (var fs = File.Create(saveasFile, result.Data.Length)) { fs.Write(result.Data, 0, result.Data.Length); fs.Flush(); } result.RefText += $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}] [Download] Success: (Remote file) ==> \"{saveasFile}\"\n"; } else { result.RefText += $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}] [Download] Error: code = {result.Code}\n"; } } catch (Exception ex) { var sb = new StringBuilder(); sb.Append($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}] [Download] Error: "); var e = ex; while (e != null) { sb.Append(e.Message + " "); e = e.InnerException; } sb.AppendLine(); result.RefCode = (int)HttpCode.USER_UNDEF; result.RefText += sb.ToString(); } return(result); }
public override bool scrappear(string url, ref Sources serverLinks, ref string error) { string buffer = string.Empty; string urlSubs = string.Empty; string urlVideo = string.Empty; List <string> urlVideos = new List <string>(); List <string> urlDescs = new List <string>(); if (0 == error.Length) { HttpManager.requestGet(url, null, ref buffer, ref error); } if (0 == error.Length) { getUrlVideoAux(buffer, ref urlVideo, ref error); } if (0 == error.Length) { HttpManager.requestGet(urlVideo, null, ref buffer, ref error); } if (0 == error.Length) { getUrlSubs(buffer, ref urlSubs, ref error); } if (0 == error.Length) { getUrlVideos(buffer, ref urlVideos, ref urlDescs, ref error); } if (0 == error.Length) { for (int k = 0; k < urlVideos.Count; k++) { serverLinks.Add(new Source(name(), urlVideos[k], urlSubs, urlDescs[k])); } } return(0 == error.Length); }
public static Promise <JoinChannelResponse> JoinChannel(string channelId, string groupId = null) { var promise = new Promise <JoinChannelResponse>(); UnityWebRequest request = null; if (string.IsNullOrEmpty(groupId)) { request = HttpManager.POST($"{Config.apiAddress}{Config.apiPath}/channels/{channelId}/join"); } else { request = HttpManager.POST($"{Config.apiAddress}{Config.apiPath}/groups/{groupId}/join"); } HttpManager.resume(request: request).Then(responseText => { promise.Resolve(JsonConvert.DeserializeObject <JoinChannelResponse>(value: responseText)); }).Catch(exception => promise.Reject(ex: exception)); return(promise); }
public static Promise <FetchCommentsResponse> FetchMessages(string channelId, string currOldestMessageId) { var promise = new Promise <FetchCommentsResponse>(); var para = new Dictionary <string, object> (); if (currOldestMessageId.isNotEmpty()) { para.Add("before", value: currOldestMessageId); } var request = HttpManager.GET($"{Config.apiAddress}{Config.apiPath}/channels/{channelId}/messages", parameter: para); HttpManager.resume(request: request).Then(responseText => { var messagesResponse = JsonConvert.DeserializeObject <FetchCommentsResponse>(value: responseText); promise.Resolve(value: messagesResponse); }).Catch(exception => promise.Reject(ex: exception)); return(promise); }
public void All() { using (var layout = new TestDirectoryLayout()) { Application.Ioc.Unregister <TemplateAreaManager>(); Application.Ioc.RegisterMany <TemplateAreaManager>(ReuseType.Singleton); var areaManager = Application.Ioc.Resolve <TemplateAreaManager>(); areaManager.GetArea("__test_area").DefaultWidgets.Add("__test"); Assert.Equals(areaManager.GetArea("__test_area").DefaultWidgets[0].Path, "__test"); layout.WritePluginFile("PluginA", "templates/__test.widget", "{ Name: 'TestWidget', CacheTime: 123, CacheBy: 'Url' }"); layout.WritePluginFile("PluginA", "templates/__test.html", "test contents {{ name }}"); var widgetInfo = areaManager.GetWidgetInfo("__test"); Assert.Equals(widgetInfo.Name, "TestWidget"); Assert.Equals(widgetInfo.CacheTime, 123); Assert.Equals(widgetInfo.CacheBy, "Url"); Assert.Equals(areaManager.GetCustomWidgets("__test_area"), null); areaManager.SetCustomWidgets("__test_area", new[] { new TemplateWidget("__custom_test") }); var customWidgets = areaManager.GetCustomWidgets("__test_area"); Assert.Equals(customWidgets.Count, 1); Assert.Equals(customWidgets[0].Path, "__custom_test"); areaManager.SetCustomWidgets("__test_area", null); Assert.Equals(areaManager.GetCustomWidgets("__test_area"), null); using (HttpManager.OverrideContext("/a", "GET")) { var context = new Context(); context["name"] = "a"; var contents = areaManager.RenderWidget(context, new TemplateWidget("__test")); Assert.IsTrueWith(contents.Contains("test contents a"), contents); } using (HttpManager.OverrideContext("/b", "GET")) { var context = new Context(); context["name"] = "b"; var contents = areaManager.RenderWidget(context, new TemplateWidget("__test")); Assert.IsTrueWith(contents.Contains("test contents b"), contents); } } }
static void Main(string[] args) { var sw = new Stopwatch(); sw.Start(); LogManager.Initialise(); ConfigManager.Initialise(); Console.Title = $"Pandora - Server Version: {ConfigManager.Config.Server.Version}"; CryptoProvider.Initialise(); DatabaseManager.Initialise(); AssetManager.Initialise(); HttpManager.Initialise(); NetworkManager.Initialise(); LogManager.Write("Game", $"Server initialised in {sw.ElapsedMilliseconds}ms"); }
public static Promise <UpdateChannelMessagesReactionResponse> UpdateReaction( string messageId, string likeEmoji, bool isRemove = false) { var promise = new Promise <UpdateChannelMessagesReactionResponse>(); var request = HttpManager.POST($"{Config.apiAddress_cn}{Config.apiPath}/messages/{messageId}/{(isRemove ? "removeReaction" : "addReaction")}", likeEmoji != null ? new Dictionary <string, object> { { "reactionType", "like" }, { "likeEmoji", likeEmoji } } : new Dictionary <string, object> { { "reactionType", "like" } }); HttpManager.resume(request: request).Then(responseText => { promise.Resolve(JsonConvert.DeserializeObject <UpdateChannelMessagesReactionResponse>(value: responseText)); }).Catch(exception => { promise.Reject(ex: exception); }); return(promise); }
public void All() { var httpContextCache = new HttpContextCache <int, string>(); using (HttpManager.OverrideContext("", "GET")) { // Put httpContextCache.Put(1, "TestDataA", TimeSpan.FromMinutes(1)); httpContextCache.Put(2, "TestDataB", TimeSpan.FromMinutes(2)); httpContextCache.Put(3, "TestDataC", TimeSpan.FromMinutes(3)); // GetOrDefault Assert.Equals(httpContextCache.GetOrDefault(1), "TestDataA"); Assert.Equals(httpContextCache.GetOrDefault(2), "TestDataB"); Assert.Equals(httpContextCache.GetOrDefault(3), "TestDataC"); Assert.Equals(httpContextCache.GetOrDefault(100), null); Assert.Equals(httpContextCache.GetOrDefault(100, "Default"), "Default"); // GetOrCreate Assert.Equals(httpContextCache.GetOrCreate( 101, () => "create 101", TimeSpan.FromSeconds(100)), "create 101"); Assert.Equals(httpContextCache.GetOrDefault(101), "create 101"); Assert.Equals(httpContextCache.GetOrCreate( 101, () => "create 101 again", TimeSpan.FromSeconds(100)), "create 101"); Assert.Equals(httpContextCache.GetOrDefault(101), "create 101"); httpContextCache.Remove(101); // Remove httpContextCache.Remove(2); httpContextCache.Remove(3); Assert.Equals(httpContextCache.Count(), 1); Assert.Equals(httpContextCache.GetOrDefault(1), "TestDataA"); Assert.Equals(httpContextCache.GetOrDefault(2), null); Assert.Equals(httpContextCache.GetOrDefault(3), null); } // Destory value after context end using (HttpManager.OverrideContext("", "GET")) { httpContextCache.Put(1, "TestDataA", TimeSpan.FromMinutes(1)); Assert.Equals(httpContextCache.GetOrDefault(1), "TestDataA"); } using (HttpManager.OverrideContext("", "GET")) { Assert.Equals(httpContextCache.GetOrDefault(1), null); } }
public static Promise <FavoriteTag> EditFavoriteTag(string tagId, IconStyle iconStyle, string name, string description = "") { var promise = new Promise <FavoriteTag>(); var para = new Dictionary <string, object> { { "id", tagId }, { "name", name }, { "description", description }, { "iconStyle", iconStyle } }; var request = HttpManager.POST($"{Config.apiAddress}{Config.apiPath}/favorite-tag/edit", parameter: para); HttpManager.resume(request: request).Then(responseText => { var editFavoriteTagResponse = JsonConvert.DeserializeObject <FavoriteTag>(value: responseText); promise.Resolve(value: editFavoriteTagResponse); }).Catch(exception => promise.Reject(ex: exception)); return(promise); }
public static Promise <Message> SendComment(string channelId, string content, string nonce, string parentMessageId = "", string upperMessageId = "") { var promise = new Promise <Message>(); var para = new SendCommentParameter { content = content, parentMessageId = parentMessageId, upperMessageId = upperMessageId, nonce = nonce, app = true }; var request = HttpManager.POST($"{Config.apiAddress}/api/connectapp/channels/{channelId}/messages", parameter: para); HttpManager.resume(request: request).Then(responseText => { var message = JsonConvert.DeserializeObject <Message>(value: responseText); promise.Resolve(value: message); }).Catch(exception => promise.Reject(ex: exception)); return(promise); }
protected override async void OnResume() { base.OnResume(); try { Car car = await HttpManager.HttpGet <Car>(String.Format(HttpManager.GetHostAddress() + "/cars/{0}", _carId)); Bitmap bmp = null; await Task.Run(() => { bmp = BitmapDownloader.GetImageBitmapFromUrl(car.Picture); }); _picture.SetImageBitmap(bmp); } catch (WebException e) { DialogProvider.ShowOkDialogWithoutAction(this, "Connection lost!", "Connection", (sender, args) => { Finish(); }); } }
public static Promise <Message> LikeComment(string commentId) { var promise = new Promise <Message>(); var para = new ReactionParameter { reactionType = "like" }; var body = JsonConvert.SerializeObject(para); var request = HttpManager.initRequest(Config.apiAddress + "/api/messages/" + commentId + "/addReaction", Method.POST); var bodyRaw = Encoding.UTF8.GetBytes(body); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.SetRequestHeader("Content-Type", "application/json"); HttpManager.resume(request).Then(responseText => { var message = JsonConvert.DeserializeObject <Message>(responseText); promise.Resolve(message); }).Catch(exception => { promise.Reject(exception); }); return(promise); }
public async Task WhenHttpManagerIsExecuted_ManagerReturnsCorrectTeamCompetitionDto() { var url = "https://validurl.com"; var teamCompetition = TeamCompetitionSource.teamCompetitions().Where(x => x.competition.code == "CL").ToList(); var httpClientMock = IHttpClientFactoryFake.Get(teamCompetition); var configurationMock = IConfigurationFake.Get(); var httpManagerMock = new HttpManager(configurationMock, httpClientMock); var competitionResult = await httpManagerMock.Get <List <TeamCompetitionDto> >(url); Assert.IsType <List <TeamCompetitionDto> >(competitionResult); Assert.Equal(12, CompetitionSource.competitions().Count()); var expectedCompetition = CompetitionSource.competitions().Where(x => x.code == "CL").FirstOrDefault(); foreach (var item in competitionResult) { Assert.Equal(expectedCompetition.code, item.competition.code); } }
public static Promise <FetchEditPersonalInfoResponse> EditPersonalInfo(string fullName, string title, string jobRoleId, string placeId) { var promise = new Promise <FetchEditPersonalInfoResponse>(); var para = new EditPersonalParameter { fullName = fullName, title = title, jobRoleId = jobRoleId, placeId = placeId }; var request = HttpManager.POST($"{Config.apiAddress}/api/updateUserBasicInfo", parameter: para); HttpManager.resume(request: request).Then(responseText => { var editPersonalInfoResponse = JsonConvert.DeserializeObject <FetchEditPersonalInfoResponse>(value: responseText); promise.Resolve(value: editPersonalInfoResponse); }).Catch(exception => promise.Reject(ex: exception)); return(promise); }
public static Promise <FetchCommentsResponse> FetchArticleComments(string channelId, string currOldestMessageId) { var promise = new Promise <FetchCommentsResponse>(); var para = new Dictionary <string, object> { { "limit", 5 } }; if (currOldestMessageId != null && currOldestMessageId.isNotEmpty()) { para.Add("before", value: currOldestMessageId); } var request = HttpManager.GET($"{Config.apiAddress}/api/connectapp/channels/{channelId}/messages", parameter: para); HttpManager.resume(request).Then(responseText => { var responseComments = JsonConvert.DeserializeObject <FetchCommentsResponse>(responseText); promise.Resolve(responseComments); }).Catch(exception => { promise.Reject(exception); }); return(promise); }
public static Promise <FetchArticleDetailResponse> FetchArticleDetail(string articleId, bool isPush = false) { var promise = new Promise <FetchArticleDetailResponse>(); var para = new Dictionary <string, object> { { "view", "true" } }; if (isPush) { para.Add("isPush", "true"); } var request = HttpManager.GET($"{Config.apiAddress}/api/connectapp/p/{articleId}", parameter: para); HttpManager.resume(request).Then(responseText => { var articleDetailResponse = JsonConvert.DeserializeObject <FetchArticleDetailResponse>(responseText); promise.Resolve(articleDetailResponse); }).Catch(exception => { promise.Reject(exception); }); return(promise); }
public static Promise ReportItem(string itemId, string itemType, string reportContext) { var promise = new Promise(); var para = new ReportParameter { itemType = itemType, itemId = itemId, reasons = new List <string> { "other:" + reportContext } }; var body = JsonConvert.SerializeObject(para); var request = HttpManager.initRequest(Config.apiAddress + "/api/report", Method.POST); var bodyRaw = Encoding.UTF8.GetBytes(body); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.SetRequestHeader("Content-Type", "application/json"); HttpManager.resume(request).Then(responseText => { promise.Resolve(); }) .Catch(exception => { promise.Reject(exception); }); return(promise); }
public void OnRequestTest_F() { OnRequestTest(() => { // test get parameter from posted file var controllerManager = Application.Ioc.Resolve <ControllerManager>(); using (HttpManager.OverrideContext("__test_action_f", HttpMethods.POST)) { var file = new HttpPostFileMock { filename = "abc.txt" }; var request = (HttpRequestMock)HttpManager.CurrentContext.Request; var response = (HttpResponseMock)HttpManager.CurrentContext.Response; request.postedFiles["file"] = file; controllerManager.OnRequest(); Assert.Equals(response.ContentType, "application/json; charset=utf-8"); var json = response.GetContentsFromBody(); var obj = JsonConvert.DeserializeObject <IDictionary <string, object> >(json); Assert.Equals(obj.GetOrDefault <string>("filename"), "abc.txt"); } }); }