public void VerifyMatchDayFilter_IfAnInvalidData_IsGiven_Then_ThrowsException() { Assert.Throws <ArgumentException>(() => HttpHelpers.VerifyFilters(new string[] { "matchday", "-1" }, authorizedFilters)); Assert.Throws <ArgumentException>(() => HttpHelpers.VerifyFilters(new string[] { "matchday", "hello" }, authorizedFilters)); Assert.DoesNotThrow(() => HttpHelpers.VerifyFilters(new string[] { "matchday", "1" }, authorizedFilters)); }
/// <summary> /// 获取设置的行业信息 /// </summary> /// <returns></returns> public async Task <string> GetIndustry() { string strUrl = string.Format("{0}?access_token={1}", WebConfigurationManager.AppSettings["GETINDUSTRY"], AccessToken), result = await HttpHelpers.GetAsync(strUrl); return(result); }
/// <summary> /// 获取模板列表,非模板库的列表 /// </summary> /// <returns></returns> public async Task <string> GetPrivateTemplates() { string strUrl = string.Format("{0}?access_token={1}", WebConfigurationManager.AppSettings["GETPRIVATETEMPLATE"], AccessToken), result = await HttpHelpers.GetAsync(strUrl); return(result); }
public ActionResult CustomerDelete(string id) { Customers customers = new Customers(); customers = HttpHelpers.SendRequestid <Customers>("http://localhost:37776", "api/Customer/DeleteCustomer", Method.GET, id); return(RedirectToAction("CustomerList")); }
/// <summary> /// 创建菜单 /// </summary> /// <param name="postJson"></param> /// <returns></returns> public async Task <string> CreateMenuAsync(string postJson) { string strUrl = string.Format("{0}?access_token={1}", WebConfigurationManager.AppSettings["CREATEMENU"], AccessToken), result = await HttpHelpers.PostAsync(strUrl, postJson); return(result); }
/// <summary> /// /// </summary> /// <param name="longurl">长链接</param> public static string GetShort(string longurl) { /* * Cookie常用的几种处理方式: * new XJHTTP().UpdateCookie("旧Cookie", "请求后的Cookie");//合并Cookie,将cookie2与cookie1合并更新 返回字符串类型Cookie * new XJHTTP().StringToCookie("网站Domain", "字符串Cookie内容");//将文字Cookie转换为CookieContainer 对象 * new XJHTTP().CookieTostring("CookieContainer 对象");//将 CookieContainer 对象转换为字符串类型 * new XJHTTP().GetAllCookie("CookieContainer 对象");//得到CookieContainer中的所有Cookie对象集合,返回List<Cookie> * new XJHTTP().GetCookieByWininet("网站Url");//从Wininet 中获取字符串Cookie 可获取IE与Webbrowser控件中的Cookie * new XJHTTP().GetAllCookieByHttpItems("请求设置对象");//从请求设置对象中获取Cookie集合,返回List<Cookie> * new XJHTTP().ClearCookie("需要处理的字符串Cookie");//清理string类型Cookie.剔除无用项返回结果为null时遇见错误. * new XJHTTP().SetIeCookie("设置Cookie的URL", "需要设置的Cookie");//可设置IE/Webbrowser控件Cookie * new XJHTTP().CleanAll();//清除IE/Webbrowser所有内容 (注意,调用本方法需要管理员权限运行) CleanHistory();清空历史记录 CleanCookie(); 清空Cookie CleanTempFiles(); 清空临时文件 */ string url = "http://api.t.sina.com.cn/short_url/shorten.json?source=4257120060&url_long=" + Encode.UrlEncode(longurl); //请求地址 string res = string.Empty; //请求结果,请求类型不是图片时有效 System.Net.CookieContainer cc = new System.Net.CookieContainer(); //自动处理Cookie对象 HttpHelpers helper = new HttpHelpers(); //发起请求对象 HttpItems items = new HttpItems(); //请求设置对象 HttpResults hr = new HttpResults(); //请求结果 items.URL = url; //设置请求地址 items.Container = cc; //自动处理Cookie时,每次提交时对cc赋值即可 hr = helper.GetHtml(items); //发起请求并得到结果 res = hr.Html; //得到请求结果 return(res); }
public async Task OnAuthentice_Available_Throws() { var builder = CreateHostBuilder(async context => { await context.Response.WriteAsync("Hello World"); }, configureKestrel: kestrelOptions => { kestrelOptions.ListenAnyIP(0, listenOptions => { listenOptions.Protocols = HttpProtocols.Http3; listenOptions.UseHttps(httpsOptions => { httpsOptions.OnAuthenticate = (_, _) => { }; }); }); }); using var host = builder.Build(); using var client = HttpHelpers.CreateClient(); var exception = await Assert.ThrowsAsync <NotSupportedException>(() => host.StartAsync().DefaultTimeout()); Assert.Equal("The OnAuthenticate callback is not supported with HTTP/3.", exception.Message); }
public void VerifyExecuteWithNineConditionalValues() { var text = "http://%3/%2/%1/$1"; var pattern = new Pattern("/([a-z]+)/index.aspx", RegexOptions.IgnoreCase | RegexOptions.Singleline); var target = new DefaultRuleAction(pattern, text); var condTest = new DefaultConditionTestValue("%{HTTP_HOST}"); var condPattern = new Pattern(@"(www)\.(.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline); var cond = MockCond(condPattern, condTest, null); Uri url = new Uri("http://www.managedfusion.com/success/index.aspx"); var httpContext = HttpHelpers.MockHttpContext(url); httpContext.Request.SetServerVariables(new Dictionary <string, string> { { "HTTP_HOST", "www.managedfusion.com" } }); var rule = MockRule(new List <ICondition> { cond }, target, null); RuleContext context = CreateRuleContext(url, httpContext, rule); target.Execute(context); Uri result = context.SubstitutedUrl; Uri expected = new Uri("http://managedfusion.com/www/www.managedfusion.com/success"); Assert.AreEqual(expected, result); }
public string ValidateWidget(string widgetXml) { GadgetModel model = new GadgetModel(); bool validationResult = true; List <string> messages = new List <string>(); try { validationResult = GadgetModel.Validate(widgetXml, messages); if (validationResult) { model = HttpHelpers.XmlDeserialize <GadgetModel>(widgetXml); } } catch (Exception ex) { validationResult = false; messages.Add(ex.Message); } return(string.Format( @"<body><script> var message=JSON.stringify({0}); top.postMessage('BinaryApiCall' + message, '*'); </script></body>" , new JavaScriptSerializer().Serialize(new { ID = Guid.NewGuid(), widget = model, manifest = widgetXml, validationResult = validationResult, messages = messages }))); }
static void WebsocketTest() { logger = new MqttNetLogger(); logger.LogMessagePublished += LoggerOnLogMessagePublished; var endpoint = Endpoint; var queryParams = new StringBuilder(); var expiresOn = DateTime.UtcNow.AddDays(2); var period = Convert.ToInt64((expiresOn.ToUniversalTime() - DateTime.UtcNow).TotalSeconds); queryParams.AppendFormat("{0}={1}", AWS4SignerBase.X_Amz_Expires, HttpHelpers.UrlEncode(period.ToString())); var headers = new Dictionary <string, string> { }; var signer = new AWS4SignerForQueryParameterAuth() { EndpointUri = new Uri(endpoint), HttpMethod = "GET", Region = "us-east-1", Service = "iotdevicegateway" }; var authorization = signer.ComputeSignature(headers, queryParams.ToString(), AWS4SignerBase.EMPTY_BODY_SHA256, ACCESS_KEY, SECRET_KEY); var urlBuilder = new StringBuilder(endpoint.ToString()); urlBuilder.AppendFormat("?{0}", queryParams.ToString()); urlBuilder.AppendFormat("&{0}", authorization); var presignedUrl = urlBuilder.ToString(); Task.Run(() => ConnectWs(presignedUrl)); }
public async Task ListFiles() { _siteSettings = _publishSettingsService.GetSettingsByPublishMethod(PublishMethods.MSDeploy); using (HttpClient httpClient = new HttpClient()) { httpClient.Timeout = TimeSpan.FromMilliseconds(10000); var requestUri = $"https://{_siteSettings.ApiUrl}/api/vfs/"; var request = new HttpRequestMessage(HttpMethod.Get, requestUri); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", HttpHelpers.GetAuthenticationString(_siteSettings)); var response = await httpClient.SendAsync( request, HttpCompletionOption.ResponseHeadersRead); if (!response.IsSuccessStatusCode) { _localLogService.Log($"Error: Count not get files from {requestUri}"); return; } var result = await response.Content.ReadAsStringAsync(); var r = result; } }
public Task <Area> GetAreaById(int idArea) { HttpHelpers.VerifyActionParameters(idArea, null, null); return(Task.Run(() => _rootArea.Areas .FirstOrDefault(T => T.Id == idArea))); }
public async Task <ActionResult> RemoveVIPs(RootModel rootModel) { try { string appId = ConfigurationManager.AppSettings["ida:AppId"]; string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"]; string response = await HttpHelpers.POST($"https://login.microsoftonline.com/{tenantName}/oauth2/v2.0/token", $"grant_type=client_credentials&client_id={appId}&client_secret={appSecret}" + "&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default"); string accessToken = response.Deserialize <TokenResponse>().access_token; graphService.accessToken = accessToken; string teamId = "f11e383b-5637-4df7-a470-afae0cc0b98b"; await graphService.DeleteAllChannel(teamId); return(DefaultView(rootModel)); } catch (Exception e) { if (e.Message == Resource.Error_AuthChallengeNeeded) { return(new EmptyResult()); } return(RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + e.Message })); } }
private async Task <string> GetToken(RootModel rootModel) { string consentPrompt = AdminConsentPromptUrl(); // for debugging only string token; if (HomeController.useAppPermissions) { string appId = ConfigurationManager.AppSettings["ida:AppId"]; string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"]; string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"]; string tenant = HomeController.tenantName; string response = await HttpHelpers.POST($"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token", $"grant_type=client_credentials&client_id={appId}&client_secret={appSecret}" + "&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default"); token = response.Deserialize <TokenResponse>().access_token; } else { token = await SampleAuthProvider.Instance.GetUserAccessTokenAsync(); } graphService.accessToken = token; return(token); }
private string test_mm() { IniHelper.FilePath = DT.ConfigPath; string cookie = DT.Cookie; HttpHelpers httpHelpers = new HttpHelpers(); HttpResults httpResults = new HttpResults(); string reString = string.Empty; string uRL = "http://pub.alimama.com/common/getUnionPubContextInfo.json"; httpResults = httpHelpers.GetHtml(new HttpItems { URL = uRL, UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0", Cookie = cookie, Allowautoredirect = true, ContentType = "application/x-www-form-urlencoded" }); reString = httpResults.Html; try { } catch (Exception) { // throw; // MessageBox.Show("系统繁忙,请稍后再试"); base.Close(); } return(reString); }
public Task <Team> GetTeamById(int idTeam) { HttpHelpers.VerifyActionParameters(idTeam, null, null); return(Task.Run(() => _rootTeam.Teams .FirstOrDefault(T => T.Id == idTeam))); }
public SoftwareItem(string url) { var html = HttpHelpers.GetUrl(url); this.Url = url; this.Parse(url); }
/// <summary> /// Gets a Graph HttpClient with a custom or default auth provider. /// </summary> /// <returns></returns> private HttpClient GetHttpClient() { var provider = GetAuthProvider(); var client = HttpHelpers.GetGraphHttpClient(provider); return(client); }
/// <summary> /// 识别证件正面 /// </summary> /// <param name="mid"></param> /// <returns></returns> private (string name, string cardid) Ocr(string mid) { HttpItems item = new HttpItems { URL = "https://pcapi.licai.cn/api/Certification/Ocr", Method = "POST", ContentType = "application/x-www-form-urlencoded;", Referer = "https://www.zhaobi.com/", UserAgent = UpLoadIMG.USERAGENT, Postdata = $"mid={mid}" }; item.Header.Add("Authorization", $"Bearer {_authorization}"); item.Header.Add("FZM-USER-IP", _userIp); item.Header.Add("FZM-REQUEST-OS", "web"); var result = new HttpHelpers().GetHtml(item).Html; #if DEBUG Console.WriteLine($"{nameof(Ocr)} result: {result}"); #endif var json = JsonConvert.DeserializeAnonymousType(result, new { data = new { address = "", birthday = "", cardid = "", name = "", nation = "", provider = "", sex = "", } }); return(json.data.name, json.data.cardid); }
[Authorize(Roles = "administrador,carga_informacion,operador")] //Obtiene todo el contexto de entidad y seguimiento activo de una entidad de la apertura activa public dynamic getSeguimientoAperturaActivaEntidad(string cod_entidad) { string token = HttpHelpers.GetTokenFromHeader(HttpContext); if (token == "") { return(Unauthorized()); } Base helper = new Base(AppSettings, token, HttpContext.Connection.RemoteIpAddress.ToString()); if (helper.Role == "carga_informacion") { cod_entidad = helper.CiaId; } dynamic seguimientoActivoEntidad = SgmntController.seguimientoAperturaActivaEntidad(cod_entidad); return(new { status = "success", mensaje = "encontrado", codigo = "200", data = seguimientoActivoEntidad }); }
public ActionResult CustomerList() { List <Customers> customers = new List <Customers>(); customers = HttpHelpers.SendRequest <List <Customers> >("http://localhost:37776", "api/Customer/CustomersList", Method.GET); return(View(customers)); }
protected override void SubscribeCore(IHttpService service) { _clusterNodeJs.RegisterControllerActions(service); _miniWebPrelude.RegisterControllerActions(service); HttpHelpers.RegisterRedirectAction(service, "/web/projections", "/web/projections.htm"); Register(service, "/projections", HttpMethod.Get, OnProjections, Codec.NoCodecs, new ICodec[] { Codec.ManualEncoding }, new Operation(Operations.Projections.List)); Register(service, "/projections/restart", HttpMethod.Post, OnProjectionsRestart, new ICodec[] { Codec.ManualEncoding }, SupportedCodecs, new Operation(Operations.Projections.Restart)); Register(service, "/projections/any", HttpMethod.Get, OnProjectionsGetAny, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.List)); Register(service, "/projections/all-non-transient", HttpMethod.Get, OnProjectionsGetAllNonTransient, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.List)); Register(service, "/projections/transient", HttpMethod.Get, OnProjectionsGetTransient, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.List)); Register(service, "/projections/onetime", HttpMethod.Get, OnProjectionsGetOneTime, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.List)); Register(service, "/projections/continuous", HttpMethod.Get, OnProjectionsGetContinuous, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.List)); Register(service, "/projections/transient?name={name}&type={type}&enabled={enabled}", HttpMethod.Post, OnProjectionsPostTransient, new ICodec[] { Codec.ManualEncoding }, SupportedCodecs, new Operation(Operations.Projections.Create).WithParameter(Operations.Projections.Parameters.Query)); Register(service, "/projections/onetime?name={name}&type={type}&enabled={enabled}&checkpoints={checkpoints}&emit={emit}&trackemittedstreams={trackemittedstreams}", HttpMethod.Post, OnProjectionsPostOneTime, new ICodec[] { Codec.ManualEncoding }, SupportedCodecs, new Operation(Operations.Projections.Create).WithParameter(Operations.Projections.Parameters.OneTime)); Register(service, "/projections/continuous?name={name}&type={type}&enabled={enabled}&emit={emit}&trackemittedstreams={trackemittedstreams}", HttpMethod.Post, OnProjectionsPostContinuous, new ICodec[] { Codec.ManualEncoding }, SupportedCodecs, new Operation(Operations.Projections.Create).WithParameter(Operations.Projections.Parameters.Continuous)); Register(service, "/projection/{name}/query?config={config}", HttpMethod.Get, OnProjectionQueryGet, Codec.NoCodecs, new ICodec[] { Codec.ManualEncoding }, new Operation(Operations.Projections.Read)); Register(service, "/projection/{name}/query?type={type}&emit={emit}", HttpMethod.Put, OnProjectionQueryPut, new ICodec[] { Codec.ManualEncoding }, SupportedCodecs, new Operation(Operations.Projections.Update)); /* source of transient projections can be set by a normal user. Authorization checks are done internally for non-transient projections. */ Register(service, "/projection/{name}", HttpMethod.Get, OnProjectionStatusGet, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Status)); Register(service, "/projection/{name}?deleteStateStream={deleteStateStream}&deleteCheckpointStream={deleteCheckpointStream}&deleteEmittedStreams={deleteEmittedStreams}", HttpMethod.Delete, OnProjectionDelete, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Delete)); Register(service, "/projection/{name}/statistics", HttpMethod.Get, OnProjectionStatisticsGet, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Statistics)); Register(service, "/projections/read-events", HttpMethod.Post, OnProjectionsReadEvents, SupportedCodecs, SupportedCodecs, new Operation(Operations.Projections.DebugProjection)); Register(service, "/projection/{name}/state?partition={partition}", HttpMethod.Get, OnProjectionStateGet, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.State)); Register(service, "/projection/{name}/result?partition={partition}", HttpMethod.Get, OnProjectionResultGet, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Result)); Register(service, "/projection/{name}/command/disable?enableRunAs={enableRunAs}", HttpMethod.Post, OnProjectionCommandDisable, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Disable)); /* transient projections can be stopped by a normal user. Authorization checks are done internally for non-transient projections.*/ Register(service, "/projection/{name}/command/enable?enableRunAs={enableRunAs}", HttpMethod.Post, OnProjectionCommandEnable, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Enable)); /* transient projections can be enabled by a normal user. Authorization checks are done internally for non-transient projections.*/ Register(service, "/projection/{name}/command/reset?enableRunAs={enableRunAs}", HttpMethod.Post, OnProjectionCommandReset, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Reset)); /* transient projections can be reset by a normal user (when debugging). Authorization checks are done internally for non-transient projections.*/ Register(service, "/projection/{name}/command/abort?enableRunAs={enableRunAs}", HttpMethod.Post, OnProjectionCommandAbort, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.Abort)); /* transient projections can be aborted by a normal user. Authorization checks are done internally for non-transient projections.*/ Register(service, "/projection/{name}/config", HttpMethod.Get, OnProjectionConfigGet, Codec.NoCodecs, SupportedCodecs, new Operation(Operations.Projections.ReadConfiguration)); Register(service, "/projection/{name}/config", HttpMethod.Put, OnProjectionConfigPut, SupportedCodecs, SupportedCodecs, new Operation(Operations.Projections.UpdateConfiguration)); }
public ActionResult GetCustomerDetail(string id) { Customers customers = new Customers(); customers = HttpHelpers.SendRequestid <Customers>("http://localhost:37776", "api/Customer/GetCustomer", Method.GET, id); return(View(customers)); }
private static void PublishMessageToTopic(string message, string topic) { var uri = new Uri($"https://<<your-iot-endpoint>>/topics/{topic}?qos=1"); Dictionary <string, string> headers = BuildHeaders(uri, message); HttpHelpers.InvokeHttpRequest(uri, "POST", headers, message); }
/// <summary> /// 删除菜单 /// </summary> /// <returns></returns> public async Task <string> DeleteMenuAsync() { string strUrl = string.Format("{0}?access_token={1}", WebConfigurationManager.AppSettings["DELETEMENU"], AccessToken), result = await HttpHelpers.GetAsync(strUrl); return(result); }
private void ProcessNode(IPublishedContent node, ref int counter, ref HttpContext context, ref List <int> templates) { if (node.TemplateId > 0) { if (templates.Contains <int>(node.TemplateId) == false) { var url = node.Url.TrimEnd(new char[] { '/' }) + "/"; try { if (url.Contains("://")) { url = url.Right(url.Length - url.IndexOf("/", url.IndexOf("://") + 3)); } templates.Add(node.TemplateId); counter++; context.Application["RebuildCacheHistory"] += node.GetTemplateAlias() + "... "; RestHelper rest = new RestHelper(); rest.Url = context.Request.Url.Scheme + "://" + HttpHelpers.GetHostWithPort(context) + url; rest.Timeout = 30000; rest.Call(); } catch (Exception e) { Debug.WriteLine("ERROR: " + e.Message); } } } }
/// <summary> /// 获得模板ID /// </summary> /// <param name="postJson"> /// {"template_id_short":"TM00015"} /// </param> /// <returns></returns> public async Task <string> GetTemplateId(string postJson) { string strUrl = string.Format("{0}?access_token={1}", WebConfigurationManager.AppSettings["GETTEMPLATEID"], AccessToken), result = await HttpHelpers.PostAsync(strUrl, postJson); return(result); }
private void waitforIp(string ip) { bool retry = true; do { HttpItems items = new HttpItems(); items.URL = @"http://www.ip138.com/ips1388.asp"; //items.ProxyIp = ip; items.Cookie = " "; //items.ProxyIp = ""; items.Timeout = 3000; HttpResults hr = new HttpHelpers().GetHtml(items); //string s = hr.StatusDescription; string reHtml = hr.Html.Replace("\r\n", "").Replace("\t", "").Replace("\n", "").Replace(" ", ""); if (reHtml.Contains("您的IP地址是")) { retry = false; reHtml = new XJHTTP().GetStringMid(reHtml, "您的IP地址是:[", "]"); //reHtml = new XJHTTP().GetStringMid(reHtml, "[", ""); } else { Tsleep(10); } }while (retry); }
/// <summary> /// 删除模板 /// </summary> /// <param name="postJson"></param> /// <returns></returns> public async Task <string> DeletePrivateTemplate(string postJson) { string strUrl = string.Format("{0}?access_token={1}", WebConfigurationManager.AppSettings["DeletePRIVATETEMPLATE"], AccessToken), result = await HttpHelpers.PostAsync(strUrl, postJson); return(result); }
public void AddFiltersToUrl_With_GivenFilter_MustThrow_ArgumentException() { var baseUrl = "http://test-url.ch"; var filters = new string[] { "test" }; Assert.Throws <ArgumentException>(() => HttpHelpers.AddFiltersToUrl(baseUrl, filters)); }