当前位置: 首页>>代码示例>>C#>>正文


C# HttpServer类代码示例

本文整理汇总了C#中HttpServer的典型用法代码示例。如果您正苦于以下问题:C# HttpServer类的具体用法?C# HttpServer怎么用?C# HttpServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpServer类属于命名空间,在下文中一共展示了HttpServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AttriubteRouting_SelectsExpectedControllerAndAction

        [InlineData("GET", "http://localhost/Customers(42)/NS.SpecialCustomer/IsSpecialUpgraded()", "IsSpecialUpgraded_42")] // function bound to derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.Routes
                .MapODataRoute("odata", "", model.Model)
                .MapODataRouteAttributes(config);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
开发者ID:quentez,项目名称:aspnetwebstack,代码行数:35,代码来源:AttributeRoutingTest.cs

示例2: ExceptionOnRequestReceived

        public void ExceptionOnRequestReceived()
        {
            using (var server = new HttpServer())
            {
                server.RequestReceived += (s, e) =>
                {
                    throw new Exception();
                };

                server.Start();

                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("http://{0}/", server.EndPoint)
                );

                try
                {
                    GetResponseFromRequest(request);
                }
                catch (WebException ex)
                {
                    var response = (HttpWebResponse)ex.Response;

                    Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode);
                    Assert.AreEqual("Internal Server Error", response.StatusDescription);
                }
            }
        }
开发者ID:smile921,项目名称:hak_blog,代码行数:28,代码来源:StatusCode.cs

示例3: QueryableLimitationTest

 public QueryableLimitationTest()
 {
     _configuration = new HttpConfiguration();
     _configuration.Routes.MapODataRoute("odata", "odata", GetEdmModel());
     HttpServer server = new HttpServer(_configuration);
     _client = new HttpClient(server);
 }
开发者ID:quentez,项目名称:aspnetwebstack,代码行数:7,代码来源:QueryableLimitationTest.cs

示例4: BasicUpload

        public void BasicUpload()
        {
            using (var server = new HttpServer())
            {
                server.RequestReceived += (s, e) =>
                {
                    Assert.That(e.Request.Form.AllKeys, Is.EquivalentTo(new[] { "key" }));
                    Assert.AreEqual("value", e.Request.Form["key"]);
                    Assert.AreEqual("multipart/form-data", e.Request.ContentType);
                    Assert.AreEqual("POST", e.Request.HttpMethod);
                    Assert.IsNull(e.Request.InputStream);
                };

                server.Start();

                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("http://{0}/", server.EndPoint)
                );

                using (var writer = new MultiPartWriter(request))
                {
                    writer.WriteValue("key", "value");
                }

                GetResponseFromRequest(request);
            }
        }
开发者ID:smile921,项目名称:hak_blog,代码行数:27,代码来源:MultiPartUpload.cs

示例5: Process

        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            if (request.UriPath.StartsWith(Url))
            {
                string hash = request.QueryString["hash"].Value;

                if (string.IsNullOrEmpty(hash))
                {
                    ThreadServerModule._404(response);
                }
                else
                {

                    if (Program.queued_files.ContainsKey(hash))
                    {
                        FileQueueStateInfo f = Program.queued_files[hash];

                        JsonObject ob = new JsonObject();

                        ob.Add("p", f.Percent().ToString());
                        ob.Add("s", string.Format("{0} / {1}", Program.format_size_string(f.Downloaded), Program.format_size_string(f.Length)));
                        ob.Add("c", f.Status == FileQueueStateInfo.DownloadStatus.Complete);

                        WriteJsonResponse(response, ob.ToString());
                    }
                    else
                    {
                        ThreadServerModule._404(response);
                    }
                }
                return true;
            }

            return false;
        }
开发者ID:tyzmodo,项目名称:chan-archiver,代码行数:35,代码来源:GetFileInfoJsonApiHandler.cs

示例6: Process

        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            if (request.UriPath.StartsWith(Url))
            {

                string board = request.QueryString[UrlParameters.Board].Value;
                string threadIdStr = request.QueryString[UrlParameters.ThreadId].Value;
                int threadId = -1;
                int.TryParse(threadIdStr, out threadId);

                if (!Program.IsBoardLetterValid(board))
                {
                    ThreadServerModule.write_text("Invalid board letter", response);
                    return true;
                }

                if (threadId <= 0)
                {
                    ThreadServerModule.write_text("Invalid thread id", response);
                    return true;
                }

                string notes = request.QueryString[UrlParameters.ThreadNotesText].Value;

                notes = System.Web.HttpUtility.HtmlDecode(notes);

                ThreadStore.GetStorageEngine().setThreadNotes(board, threadId, notes);

                response.Redirect(ThreadServerModule.GetThreadPageLink(board, threadId));

                return true;
            }
            return false;
        }
开发者ID:tyzmodo,项目名称:chan-archiver,代码行数:34,代码来源:ThreadNotesHandler.cs

示例7: Main

    static void Main()
    {
        var ledActuator = new DigitalActuator
        {
            OutputPin = Parameters.LedPin
        };

        var webServer = new HttpServer
        {
            // RelayDomain = Parameters.RelayDomain,
            // RelaySecretKey = Parameters.RelaySecretKey,
            RequestRouting =
            {
                {
                    "PUT /led/target",
                    new ManipulatedVariable
                    {
                        FromHttpRequest =
                            CSharpRepresentation.TryDeserializeBool,
                        ToActuator = ledActuator.HandlePut
                    }.HandleRequest
                },
                {
                    "GET /led/target.html",
                    HandleLedTargetHtml
                }
            }
        };

        webServer.Run();
    }
开发者ID:jchidley,项目名称:GSIOT-NP2,代码行数:31,代码来源:Program.cs

示例8: SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders

        public void SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders(string requestedMethod, string expectedOrigin, string requestedHeaders)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default", "{controller}");
            HttpServer server = new HttpServer(config);
            CorsMessageHandler corsHandler = new CorsMessageHandler(config);
            corsHandler.InnerHandler = server;
            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample");
            request.SetConfiguration(config);
            request.Headers.Add(CorsConstants.Origin, "http://localhost");
            request.Headers.Add(CorsConstants.AccessControlRequestMethod, requestedMethod);
            request.Headers.Add(CorsConstants.AccessControlRequestHeaders, requestedHeaders);

            HttpResponseMessage response = invoker.SendAsync(request, CancellationToken.None).Result;
            string origin = response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault();
            string allowMethod = response.Headers.GetValues(CorsConstants.AccessControlAllowMethods).FirstOrDefault();
            string[] allowHeaders = response.Headers.GetValues(CorsConstants.AccessControlAllowHeaders).FirstOrDefault().Split(',');
            string[] requestedHeaderArray = requestedHeaders.Split(',');

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedOrigin, origin);
            Assert.Equal(requestedMethod, allowMethod);
            foreach (string requestedHeader in requestedHeaderArray)
            {
                Assert.Contains(requestedHeader, allowHeaders);
            }
        }
开发者ID:normalian,项目名称:aspnetwebstack,代码行数:28,代码来源:CorsMessageHandlerTest.cs

示例9: CometCommandHandlerPipeline

        public CometCommandHandlerPipeline(HttpServer server)
        {
            if (server == null)
                throw new Exception("HttpServer cannot be null.");

            Server = server;
        }
开发者ID:jeanmahai,项目名称:PublicTools,代码行数:7,代码来源:CometCommandHandlerPipeline.cs

示例10: QueryStringKeyWithMultipleValues

        public void QueryStringKeyWithMultipleValues()
        {
            using (var server = new HttpServer())
            {
                server.RequestReceived += (s, e) =>
                {
                    Assert.That(e.Request.QueryString.AllKeys, Is.EquivalentTo(new[] { "key" }));
                    Assert.That(e.Request.QueryString.GetValues("key"), Is.EquivalentTo(new[] { "first", "second", "third" }));
                    Assert.AreEqual(e.Request.QueryString["key"], "first,second,third");

                    using (var writer = new StreamWriter(e.Response.OutputStream))
                    {
                        writer.Write(ResponseText);
                    }
                };

                server.Start();

                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("http://{0}/?key=first&key=second&key=third", server.EndPoint)
                );

                Assert.AreEqual(ResponseText, GetResponseFromRequest(request));
            }
        }
开发者ID:Cocotus,项目名称:NHttp,代码行数:25,代码来源:BasicRequest.cs

示例11: Main

        static void Main(string[] args)
        {
            // Template generators are used to render templates 
            // (convert code + html to pure html).
            TemplateManager mgr = new TemplateManager();
            mgr.Add("haml", new HamlGenerator());

            // The httpserver is quite dumb and will only serve http, nothing else.
            HttpServer server  = new HttpServer();

            // a controller mode implements a MVC pattern
            // You'll add all controllers to the same module.
            ControllerModule mod = new ControllerModule();
            mod.Add(new UserController(mgr));
            server.Add(mod);

            // file module will be handling files
            FileModule fh = new FileModule("/", Environment.CurrentDirectory);
            fh.AddDefaultMimeTypes();
            server.Add(fh);

            // Let's start pure HTTP, we can also start a HTTPS listener.
            server.Start(IPAddress.Any, 8081);

            Console.ReadLine();
        }
开发者ID:kf6kjg,项目名称:halcyon,代码行数:26,代码来源:Program.cs

示例12: Main

        static void Main(string[] args)
        {
            HttpServer http = new HttpServer();

            http.ProcessRequest = (request, response) =>
            {
                Console.WriteLine(request.Url);

                if (request.Url != "/foo")
                {
                    response.WriteLine("Hello from {0}.", request.Url);
                }
                else
                {
                    response.StatusCode = HttpStatusCode.NotFound;
                }
            };

            http.Start();

            Console.WriteLine("Press enter to stop HTTP server.");
            Console.ReadLine();

            http.Stop();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
开发者ID:smack0007,项目名称:Grapevine,代码行数:28,代码来源:Program.cs

示例13: GetWithErrorXmlTest

 public void GetWithErrorXmlTest()
 {
     using (var server = new HttpServer(new RequestHandler
     {
         EstimatedMethod = "GET",
         EstimatedPathAndQuery = string.Format("/v1.0/accounts/{0}/tnreservation/1", Helper.AccountId),
         ContentToSend = new StringContent(TestXmlStrings.InvalidReservationResponseXml, Encoding.UTF8, "application/xml")
     }))
     {
         var client = Helper.CreateClient();
         try
         {
             TnReservation.Get(client, "1").Wait();
             if (server.Error != null) throw server.Error;
         }
         catch (AggregateException exc)
         {
             var ex = exc.InnerExceptions[0] as BandwidthIrisException;
             if (ex != null)
             {
                 Assert.AreEqual("Reservation failed: telephone number 9195551212 is not available.", ex.Message);
                 Assert.AreEqual("5041", ex.Code);
                 return;
             }
         }
         Assert.Fail("should throw an error");
     }
 }
开发者ID:dwimsey,项目名称:csharp-bandwidth-iris,代码行数:28,代码来源:TnReservationTests.cs

示例14: GetTest

 public void GetTest()
 {
     var item = new Site
     {
         Id = "1",
         Name = "Name",
         Address = new Address
         {
             City = "City",
             Country = "County"
         }
     };
     using (var server = new HttpServer(new RequestHandler
     {
         EstimatedMethod = "GET",
         EstimatedPathAndQuery = string.Format("/v1.0/accounts/{0}/sites/1", Helper.AccountId),
         ContentToSend = Helper.CreateXmlContent(new SiteResponse{Site = item})
     }))
     {
         var client = Helper.CreateClient();
         var result = Site.Get(client, "1").Result;
         if (server.Error != null) throw server.Error;
         Helper.AssertObjects(item, result);
     }
 }
开发者ID:dwimsey,项目名称:csharp-bandwidth-iris,代码行数:25,代码来源:SiteTests.cs

示例15: Main

    public static void Main()
    {
        var thdLed = new Thread(HandleLed);
        thdLed.Start();

        var digitalSensor = new DigitalSensor { InputPin = Pins.GPIO_PIN_D12 };
        var analogSensor = new AnalogSensor { InputPin = Pins.GPIO_PIN_A1, MinValue = 0.0, MaxValue = 3.3 };
        var lowPort = new OutputPort(Pins.GPIO_PIN_A0, false);
        var highPort = new OutputPort(Pins.GPIO_PIN_A2, true);

        var ledActuator = new DigitalActuator { OutputPin = Pins.GPIO_PIN_D13 };
        //need to create HTTP PUTs!

        var webServer = new HttpServer
        {
            RelayDomain = "gsiot-bcjp-yj88",
            RelaySecretKey = "HDMvyM11hAu6H6cxIaT50dL9ALWc81MYB8H/UFhV",
            RequestRouting =
            {
                { "GET /hello*", HandleHello }, //This accepts a lot of URLs
                { "GET /on", HandleOn },
                { "GET /off", HandleOff },
                { "POST /on", HandlePostOn },
                { "POST /off", HandlePostOff },
                { "GET /d12", new MeasuredVariable{ FromSensor=digitalSensor.HandleGet}.HandleRequest},
                { "GET /a1", new MeasuredVariable{ FromSensor=analogSensor.HandleGet}.HandleRequest},
                { "PUT /d13", new ManipulatedVariable{ FromHttpRequest=CSharpRepresentation.TryDeserializeBool,ToActuator=ledActuator.HandlePut}.HandleRequest},
            }
        };
        webServer.Run();
    }
开发者ID:refap3,项目名称:refAP3repo,代码行数:31,代码来源:HelloWeb.cs


注:本文中的HttpServer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。