• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# HttpListenerContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: GetPeople

        public bool GetPeople(WebServer server, HttpListenerContext context)
        {
            try
            {
                // read the last segment
                var lastSegment = context.Request.Url.Segments.Last();

                // if it ends with a / means we need to list people
                if (lastSegment.EndsWith("/"))
                    return context.JsonResponse(PeopleRepository.Database);

                // otherwise, we need to parse the key and respond with the entity accordingly
                int key;

                if (int.TryParse(lastSegment, out key) && PeopleRepository.Database.Any(p => p.Key == key))
                {
                    return context.JsonResponse(PeopleRepository.Database.FirstOrDefault(p => p.Key == key));
                }

                throw new KeyNotFoundException("Key Not Found: " + lastSegment);
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return context.JsonResponse(ex);
            }
        }
开发者ID:unosquare,项目名称:embedio,代码行数:27,代码来源:TestController.cs


示例2: ResponseHandler

	static void ResponseHandler (HttpListenerContext httpContext)
	{
		byte [] buffer = Encoding.ASCII.GetBytes ("hello world");
		httpContext.Response.StatusCode = 200;
		httpContext.Response.OutputStream.Write (buffer, 0, buffer.Length);
		httpContext.Response.Close ();
	}
开发者ID:mono,项目名称:gert,代码行数:7,代码来源:server.cs


示例3: ProcessRequest

    public IEnumerator ProcessRequest(HttpListenerContext context, System.Action<bool> isMatch)
    {
        string url = context.Request.RawUrl;

        //Debug.Log (url);

        bool match = false;
        foreach(Regex regex in regexList)
        {
            if (regex.Match(url).Success)
            {
                match = true;
                break;
            }
        }

        if (!match)
        {
            isMatch(false);
            yield break;
        }

        IEnumerator e = OnRequest(context);
        do
        {
            yield return null;
        }
        while (e.MoveNext());

        isMatch(true);
    }
开发者ID:FomTarro,项目名称:CrimeTimeUNET,代码行数:31,代码来源:WebServerRule.cs


示例4: OnRequest

    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        Debug.Log ("Some Random String");
        HttpListenerResponse response = context.Response;
        Stream stream = response.OutputStream;

        response.ContentType = "application/octet-stream";

        byte[] data = unityWebPackage.bytes;

        int i = 0;
        int count = data.Length;

        while(i < count)
        {
            if (i != 0)
                yield return null;

            int writeLength = Math.Min((int)writeStaggerCount, count - i);

            stream.Write(data, i, writeLength);

            i += writeLength;
        }
    }
开发者ID:bonbombs,项目名称:CrimeTimeUNET,代码行数:25,代码来源:UnityWebPlayerRule.cs


示例5: OnRequest

    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        Debug.Log("Hello:" + context.Request.UserHostAddress);

        string html = htmlPage.text;

        foreach(HtmlKeyValue pair in substitutions)
        {
            html = html.Replace(string.Format("${0}$", pair.Key), pair.Value);
        }

        html = ModifyHtml(html);

        byte[] data = Encoding.ASCII.GetBytes(html);

        yield return null;

        HttpListenerResponse response = context.Response;

        response.ContentType = "text/html";

        Stream responseStream = response.OutputStream;

        int count = data.Length;
        int i = 0;
        while(i < count)
        {
            if (i != 0)
                yield return null;

            int writeLength = Math.Min((int)writeStaggerCount, count - i);
            responseStream.Write(data, i, writeLength);
            i += writeLength;
        }
    }
开发者ID:FomTarro,项目名称:CrimeTimeUNET,代码行数:35,代码来源:HtmlRule.cs


示例6: HttpListenerWebSocketContext

   internal HttpListenerWebSocketContext(
 HttpListenerContext context, Logger logger)
   {
       _context = context;
         _stream = WsStream.CreateServerStream (context);
         _websocket = new WebSocket (this, logger ?? new Logger ());
   }
开发者ID:uken,项目名称:websocket-sharp,代码行数:7,代码来源:HttpListenerWebSocketContext.cs


示例7: Handle

    public void Handle(HttpListenerContext context)
    {
        HttpListenerResponse response = context.Response;

        // Get device data
        string id = context.Request.QueryString["id"];
        Device device = _deviceManager.FindDeviceByID(id);

        // Create response
        string message = "{\"Version\":\"2.0.1\", \"Auth\": \"";
        response.StatusCode = (int)HttpStatusCode.OK;

        if (device != null || !_deviceManager.AuthenticationEnabled) {
            message += "OK\"}";
        } else {
            message += "DENIED\"}";
        }

        // Fill in response body
        byte[] messageBytes = Encoding.Default.GetBytes(message);
        response.OutputStream.Write(messageBytes, 0, messageBytes.Length);
        response.ContentType = "application/json";

        // Send the HTTP response to the client
        response.Close();
    }
开发者ID:sakisds,项目名称:Icy-Monitor,代码行数:26,代码来源:AuthHttpRequestHandler.cs


示例8: GetPeople

        public bool GetPeople(WebServer server, HttpListenerContext context)
        {
            try
            {
                // read the last segment
                var lastSegment = context.Request.Url.Segments.Last();

                // if it ends with a / means we need to list people
                if (lastSegment.EndsWith("/"))
                    return context.JsonResponse(_dbContext.People.SelectAll());

                // if it ends with "first" means we need to show first record of people
                if (lastSegment.EndsWith("first"))
                    return context.JsonResponse(_dbContext.People.SelectAll().First());

                // otherwise, we need to parse the key and respond with the entity accordingly
                int key = 0;
                if (int.TryParse(lastSegment, out key))
                {
                    var single = _dbContext.People.Single(key);

                    if (single != null)
                        return context.JsonResponse(single);
                }

                throw new KeyNotFoundException("Key Not Found: " + lastSegment);
            }
            catch (Exception ex)
            {
                // here the error handler will respond with a generic 500 HTTP code a JSON-encoded object
                // with error info. You will need to handle HTTP status codes correctly depending on the situation.
                // For example, for keys that are not found, ou will need to respond with a 404 status code.
                return HandleError(context, ex, (int)System.Net.HttpStatusCode.InternalServerError);
            }
        }
开发者ID:unosquare,项目名称:embedio,代码行数:35,代码来源:PeopleController.cs


示例9: HttpListenerHost

            public HttpListenerHost(HttpListenerContext context, string serviceUri)
            {
                this.httpListenerContext = context;

                // retrieve request information from HttpListenerContext
                HttpListenerRequest contextRequest = context.Request;
                this.AbsoluteRequestUri = new Uri(contextRequest.Url.AbsoluteUri);
                this.AbsoluteServiceUri = new Uri(serviceUri);
                this.RequestPathInfo = this.AbsoluteRequestUri.MakeRelativeUri(this.AbsoluteServiceUri).ToString();

                // retrieve request headers
                this.RequestAccept = contextRequest.Headers[HttpAccept];
                this.RequestAcceptCharSet = contextRequest.Headers[HttpAcceptCharset];
                this.RequestIfMatch = contextRequest.Headers[HttpIfMatch];
                this.RequestIfNoneMatch = contextRequest.Headers[HttpIfNoneMatch];
                this.RequestMaxVersion = contextRequest.Headers[HttpMaxDataServiceVersion];
                this.RequestVersion = contextRequest.Headers[HttpDataServiceVersion];
                this.RequestContentType = contextRequest.ContentType;

                this.RequestHeaders = new WebHeaderCollection();
                foreach (string header in contextRequest.Headers.AllKeys)
                    this.RequestHeaders.Add(header, contextRequest.Headers.Get(header));

                this.QueryStringValues = new Dictionary<string, string>();
                string queryString = this.AbsoluteRequestUri.Query;
                var parsedValues = HttpUtility.ParseQueryString(queryString);
                foreach (string option in parsedValues.AllKeys)
                    this.QueryStringValues.Add(option, parsedValues.Get(option));

                processExceptionCalled = false;
            }
开发者ID:larsenjo,项目名称:odata.net,代码行数:31,代码来源:IDataServiceHostRunner.cs


示例10: HandleReqest

        /// <summary>
        /// Request handler function. Overriden from RequestHandler class
        /// </summary>
        /// <param name="context">Request context</param>
        public override void HandleReqest(HttpListenerContext context)
        {
            _content.Append(TemplateText);

            if (context.Request.HttpMethod == "GET")
            {
                if (GetHandler != null)
                {
                    GetHandler(this, new HTTPEventArgs(EmbeddedHttpServer.GetFileName(context.Request.RawUrl), context.Request.QueryString));
                }
            }

            if (TemplateTags != null)
            {
                foreach (var keyvaluepair in TemplateTags)
                {
                    var toreplace = "{{" + keyvaluepair.Key + "}}";
                    _content.Replace(toreplace, keyvaluepair.Value.ToString());
                }
            }

            MarkdownSharp.Markdown md = new MarkdownSharp.Markdown();

            var output = Encoding.UTF8.GetBytes(BaseHTMLTemplate.Replace("{{md}}", md.Transform(_content.ToString())));
            context.Response.ContentType = "text/html";
            context.Response.ContentLength64 = output.Length;
            context.Response.OutputStream.Write(output, 0, output.Length);
        }
开发者ID:webmaster442,项目名称:EmbeddedHttpServer,代码行数:32,代码来源:MarkDownTemplateHandler.cs


示例11: HttpListenerRequest

		internal HttpListenerRequest (HttpListenerContext context)
		{
			this.context = context;
			headers = new WebHeaderCollection ();
			input_stream = Stream.Null;
			version = HttpVersion.Version10;
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:7,代码来源:HttpListenerRequest.cs


示例12: HttpListenerRequest

 internal HttpListenerRequest(HttpListenerContext context)
 {
     _context = context;
     _contentLength = -1;
     _headers = new WebHeaderCollection ();
     _identifier = Guid.NewGuid ();
     _version = HttpVersion.Version10;
 }
开发者ID:richardfeng,项目名称:UnitySocketIO-WebSocketSharp,代码行数:8,代码来源:HttpListenerRequest.cs


示例13: ChunkedInputStream

		public ChunkedInputStream (
			HttpListenerContext context, Stream stream, byte [] buffer, int offset, int length)
			: base (stream, buffer, offset, length)
		{
			this.context = context;
			WebHeaderCollection coll = (WebHeaderCollection) context.Request.Headers;
			decoder = new ChunkStream (coll);
		}
开发者ID:fengxianqi,项目名称:Youbang,代码行数:8,代码来源:ChunkedInputStream.cs


示例14: HttpListenerRequest

        internal HttpListenerRequest(HttpListenerContext context)
        {
            this.context = context;

            headers = new WebHeaderCollection();

            version = HttpVersion.Version10;
        }
开发者ID:jamesaxl,项目名称:reactor,代码行数:8,代码来源:HttpListenerRequest.cs


示例15: InvokeHandler

 private void InvokeHandler(IHttpRequestHandler handler, HttpListenerContext context)
 {
     if (handler == null)
         return;
     Console.WriteLine("Request being handled");
     HandleHttpRequestCommand command = new HandleHttpRequestCommand(handler, context);
     Thread commandThread = new Thread(command.Execute);
     commandThread.Start();
 }
开发者ID:jordanbang,项目名称:MusicDiff-Windows,代码行数:9,代码来源:HttpResourceLocator.cs


示例16: InvokeHandler

 private void InvokeHandler(HttpRequestHandler handler,
     HttpListenerContext context)
 {
     // Start a new thread to invoke the handler to process the HTTP request
     HandleHttpRequestCommand handleHttpRequestCommand
         = new HandleHttpRequestCommand(handler, context);
     Thread handleHttpRequestThread = new Thread(handleHttpRequestCommand.Execute);
     handleHttpRequestThread.Start();
 }
开发者ID:sakisds,项目名称:Icy-Monitor,代码行数:9,代码来源:HttpResourceLocator.cs


示例17: Handle

 public void Handle(HttpListenerContext context)
 {
     HttpListenerResponse resp = context.Response;
     string message = "you just sent me a message";
     byte[] bytes = Encoding.Default.GetBytes(message);
     resp.OutputStream.Write(bytes, 0, bytes.Length);
     resp.Close();
     Console.WriteLine("handled diff sync request");
 }
开发者ID:jordanbang,项目名称:MusicDiff-Windows,代码行数:9,代码来源:DiffSyncRequestHandler.cs


示例18: Handle

    public void Handle(HttpListenerContext context)
    {
        HttpListenerResponse serverResponse = context.Response;

        // Indicate the failure as a 404 not found
        serverResponse.StatusCode = (int) HttpStatusCode.BadRequest;

        // Send the HTTP response to the client
        serverResponse.Close();
    }
开发者ID:sakisds,项目名称:Icy-Monitor,代码行数:10,代码来源:InvalidHttpRequestHandler.cs


示例19: Handle

    public void Handle(HttpListenerContext context)
    {
        HttpListenerResponse response = context.Response;

        // Get query data
        string type = context.Request.QueryString["type"];
        string names = context.Request.QueryString["name"];
        string id = context.Request.QueryString["id"];
        string message = "";

        // Authenticate
        bool authorized = true;
        DeviceManager dm = _parent.GetDeviceManager();
        if (dm.FindDeviceByID(id) == null && dm.AuthenticationEnabled) {
            response.StatusCode = (int) HttpStatusCode.Unauthorized;
            message = "401 Unauthorized";
            authorized = false;
        }

        // Check what kind of data is requested
        if (type != null && authorized) {
            response.StatusCode = (int)HttpStatusCode.OK;
            switch (type) {
                case "cpu": message = HandleCPU(names); break;
                case "gpu": message = HandleGPU(names); break;
                case "fs": message = HandleFilesystems(); break;
                case "processes": message = HandleProcesses(context.Request.QueryString["sort"]); break;
                case "system": message = HandleSystem(names); break;
                case "disks": message = HandleDisks(); break;
                case "listdev": message = HandleListDevices(); break;
                case "history": message = HandleHistory(); break;
                case "historyfile": message = HandleHistoryFile(context.Request.QueryString["file"]); break;
                case "historylist": message = HandleHistoryList(context.Request.QueryString["sort"]); break;
                case "overview": message = HandleOverview(); break;
                case "addnotif": message = HandleAddNotification(context.Request.QueryString["id"], context.Request.QueryString["name"],
                    context.Request.QueryString["ntype"], context.Request.QueryString["condition"], context.Request.QueryString["value"], context.Request.QueryString["ringonce"]);
                    break;
                case "listnotif": message = HandleGetNotifications(context.Request.QueryString["id"]); break;
                case "remnotif": message = HandleRemoveNotification(context.Request.QueryString["id"], context.Request.QueryString["index"]); break;
                case "testnotif": message = HandleTestNotification(context.Request.QueryString["id"]); break;
            }
        } else if (authorized) {
            response.StatusCode = (int) HttpStatusCode.BadRequest;
            message = "400 Bad request";
        }

        // Send the HTTP response to the client
        response.ContentType = "application/json";
        byte[] messageBytes = Encoding.Default.GetBytes(message);
        response.OutputStream.Write(messageBytes, 0, messageBytes.Length);
        response.Close();
    }
开发者ID:sakisds,项目名称:Icy-Monitor,代码行数:52,代码来源:DataHttpRequestHandler.cs


示例20: OnRequest

    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        HttpListenerRequest request = context.Request;
        TextAsset textItem;
        byte[] data = new byte[0];
        string url = request.RawUrl;
        //Debug.Log ("RAW: " + url);

        string subFolder = "";
        string[] directories = url.Split ('/');
        for (int s = urlRegexList [0].Split('/').Length - 1; s < directories.Length - 1; s++)
            subFolder += directories [s]+"/";

        string item = url.Substring(url.LastIndexOf('/') + 1);
        //Debug.Log ("ITEM: " + item);

        string itemName = item.Substring(0, item.IndexOf('.'));
        //Debug.Log ("NAME: " + itemName);

        string path = string.Format ("{0}{1}", subFolder, itemName);
        Debug.Log ("PATH: " + path);

        try {
            //Debug.Log (Resources.Load (path).GetType ().ToString ());
            textItem = Resources.Load(path) as TextAsset;
            data = textItem.bytes;
        } catch (Exception e){
            Debug.Log("Cannot produce asset at path: " + path + " with Exception: " + e.Message);
        }

        yield return null;

        ///

        HttpListenerResponse response = context.Response;

        response.ContentType = "text/html";

        Stream responseStream = response.OutputStream;

        int count = data.Length;
        int i = 0;
            while (i < count)
            {
                if (i != 0)
                    yield return null;

                int writeLength = Math.Min((int)writeStaggerCount, count - i);
                responseStream.Write(data, i, writeLength);
                i += writeLength;
            }
    }
开发者ID:FomTarro,项目名称:CrimeTimeUNET,代码行数:52,代码来源:ResourcesRule.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# HttpMessageHandlerMock类代码示例发布时间:2022-05-24
下一篇:
C# HttpListener类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap