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


C# IHttpRequest.CreateResponse方法代码示例

本文整理汇总了C#中IHttpRequest.CreateResponse方法的典型用法代码示例。如果您正苦于以下问题:C# IHttpRequest.CreateResponse方法的具体用法?C# IHttpRequest.CreateResponse怎么用?C# IHttpRequest.CreateResponse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IHttpRequest的用法示例。


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

示例1: FileModuleTest

 public FileModuleTest()
 {
     _request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
 	_context = new HttpResponseContext();
 	_response = _request.CreateResponse(_context);
     _module = new FileModule("/files/", Environment.CurrentDirectory);
     _module.MimeTypes.Add("txt", "text/plain");
 }
开发者ID:kf6kjg,项目名称:halcyon,代码行数:8,代码来源:FileModuleTest.cs

示例2: ControllerModuleTest

 public ControllerModuleTest()
 {
     _controller = new TestController();
     _request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
 	_context = new HttpResponseContext();
 	_response = _request.CreateResponse(_context);
     _module = new ControllerModule();
 }
开发者ID:kow,项目名称:Aurora-Sim,代码行数:8,代码来源:ControllerModuleTest.cs

示例3: RequestControllerTest

 public RequestControllerTest()
 {
     _controller = new MyController();
     _request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
 	_stream = new MyStream();
     _context = new HttpResponseContext();
     _response = _request.CreateResponse(_context);
 }
开发者ID:kf6kjg,项目名称:halcyon,代码行数:8,代码来源:RequestControllerTest.cs

示例4: ReverseProxyTest

        public ReverseProxyTest()
        {
            _request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
        	_stream = new MyStream();
            _context = new HttpResponseContext();
        	_response = _request.CreateResponse(_context);
            _module = new ReverseProxyModule("http://localhost/", "http://localhost:4210/");
			_server = new HttpServer();
            
        }
开发者ID:kf6kjg,项目名称:halcyon,代码行数:10,代码来源:ReverseProxyTest.cs

示例5: HandleHTTPRequest

 /// <summary>
 /// Handles SUBSCRIBE and UNSUBSCRIBE HTTP requests.
 /// </summary>
 /// <param name="request">The HTTP request instance to handle</param>
 /// <param name="context">The HTTP client context of the specified <paramref name="request"/>.</param>
 /// <param name="config">The UPnP endpoint over that the HTTP request was received.</param>
 /// <returns><c>true</c> if the request could be handled and a HTTP response was sent, else <c>false</c>.</returns>
 public bool HandleHTTPRequest(IHttpRequest request, IHttpClientContext context, EndpointConfiguration config)
 {
   if (request.Method == "SUBSCRIBE")
   { // SUBSCRIBE events
     string pathAndQuery = request.Uri.PathAndQuery;
     DvService service;
     if (config.EventSubPathsToServices.TryGetValue(pathAndQuery, out service))
     {
       IHttpResponse response = request.CreateResponse(context);
       string httpVersion = request.HttpVersion;
       string userAgentStr = request.Headers.Get("USER-AGENT");
       string callbackURLsStr = request.Headers.Get("CALLBACK");
       string nt = request.Headers.Get("NT");
       string sid = request.Headers.Get("SID");
       string timeoutStr = request.Headers.Get("TIMEOUT");
       int timeout = UPnPConsts.GENA_DEFAULT_SUBSCRIPTION_TIMEOUT;
       ICollection<string> callbackURLs = null;
       if ((!string.IsNullOrEmpty(timeoutStr) && (!timeoutStr.StartsWith("Second-") ||
           !int.TryParse(timeoutStr.Substring("Second-".Length).Trim(), out timeout))) ||
           (!string.IsNullOrEmpty(callbackURLsStr) &&
           !TryParseCallbackURLs(callbackURLsStr, out callbackURLs)))
       {
         response.Status = HttpStatusCode.BadRequest;
         response.Send();
         return true;
       }
       if (!string.IsNullOrEmpty(sid) && (callbackURLs != null || !string.IsNullOrEmpty(nt)))
       {
         response.Status = HttpStatusCode.BadRequest;
         response.Reason = "Incompatible Header Fields";
         response.Send();
         return true;
       }
       if (callbackURLs != null && !string.IsNullOrEmpty(nt))
       { // Subscription
         bool subscriberSupportsUPnP11;
         try
         {
           if (string.IsNullOrEmpty(userAgentStr))
             subscriberSupportsUPnP11 = false;
           else
           {
             int minorVersion;
             if (!ParserHelper.ParseUserAgentUPnP1MinorVersion(userAgentStr, out minorVersion))
             {
               response.Status = HttpStatusCode.BadRequest;
               response.Send();
               return true;
             }
             subscriberSupportsUPnP11 = minorVersion >= 1;
           }
         }
         catch (Exception e)
         {
           UPnPConfiguration.LOGGER.Warn("GENAServerController: Error in event subscription", e);
           response.Status = HttpStatusCode.BadRequest;
           response.Send();
           return true;
         }
         if (service.HasComplexStateVariables && !subscriberSupportsUPnP11)
         {
           response.Status = HttpStatusCode.ServiceUnavailable;
           response.Send();
           return true;
         }
         bool validURLs = callbackURLs.All(url => url.StartsWith("http://"));
         if (nt != "upnp:event" || !validURLs)
         {
           response.Status = HttpStatusCode.PreconditionFailed;
           response.Reason = "Precondition Failed";
           response.Send();
           return true;
         }
         DateTime date;
         if (Subscribe(config, service, callbackURLs, httpVersion, subscriberSupportsUPnP11, ref timeout,
             out date, out sid))
         {
           response.Status = HttpStatusCode.OK;
           response.AddHeader("DATE", date.ToUniversalTime().ToString("R"));
           response.AddHeader("SERVER", UPnPConfiguration.UPnPMachineInfoHeader);
           response.AddHeader("SID", sid);
           response.AddHeader("CONTENT-LENGTH", "0");
           response.AddHeader("TIMEOUT", "Second-"+timeout);
           response.Send();
           SendInitialEventNotification(sid);
           return true;
         }
         response.Status = HttpStatusCode.ServiceUnavailable;
         response.Reason = "Unable to accept renewal"; // See (DevArch), table 4-4
         response.Send();
         return true;
       }
       if (!string.IsNullOrEmpty(sid))
//.........这里部分代码省略.........
开发者ID:chekiI,项目名称:MediaPortal-2,代码行数:101,代码来源:GENAServerController.cs

示例6: ProcessRequest

		private void ProcessRequest(IHttpClientContext context, IHttpRequest request)
		{
			IHttpResponse response = request.CreateResponse(context);
			try
			{
				foreach (IRule rule in _rules)
				{
					if (!rule.Process(request, response))
						continue;
					response.Send();
					return;
				}

				// load cookies if the exist.
				RequestCookies cookies = request.Headers["cookie"] != null
											 ? new RequestCookies(request.Headers["cookie"])
											 : new RequestCookies(string.Empty);

				request.SetCookies(cookies);

				IHttpSession session;
				if (cookies[_sessionCookieName] != null)
				{
					string sessionCookie = cookies[_sessionCookieName].Value;

					// there's a bug somewhere which messes up headers which can render the session cookie useless.
					// therefore let's consider the session cookie as not set if that have happened.
					if (sessionCookie.Length > 40)
					{
						_logWriter.Write(this, LogPrio.Error, "Session cookie is invalid: " + sessionCookie);
						cookies.Remove(_sessionCookieName);
						_sessionStore.Remove(sessionCookie); // free the session cookie (and thus generating a new one).
						session = _sessionStore.Create();
					}
					else
						session = _sessionStore.Load(sessionCookie) ??
								  _sessionStore.Create(sessionCookie);
				}
				else
					session = _sessionStore.Create();

				HandleRequest(context, request, response, session);
			}
			catch (Exception err)
			{
				if (_exceptionHandler == null)
#if DEBUG
					throw;
#else
				{
					WriteLog(LogPrio.Fatal, err.Message);
					return;
				}
#endif
				_exceptionHandler(this, err);

				Exception e = err;
				while (e != null)
				{
					if (e is SocketException)
						return;

					e = e.InnerException;
				}

				try
				{
#if DEBUG
					context.Respond("HTTP/1.0", HttpStatusCode.InternalServerError, "Internal server error", err.ToString(), "text/plain");
#else
					context.Respond("HTTP/1.0", HttpStatusCode.InternalServerError, "Internal server error");
#endif
				}
				catch (Exception err2)
				{
					LogWriter.Write(this, LogPrio.Fatal, "Failed to respond on message with Internal Server Error: " + err2);
				}


			}
		}
开发者ID:kf6kjg,项目名称:halcyon,代码行数:81,代码来源:HttpServer.cs

示例7: HandleHTTPRequest_NoLock

    /// <summary>
    /// Handles all kinds of HTTP over TCP requests - Description, Control and Event subscriptions.
    /// </summary>
    /// <param name="context">HTTP client context of the current request.</param>
    /// <param name="request">HTTP request to handle.</param>
    protected void HandleHTTPRequest_NoLock(IHttpClientContext context, IHttpRequest request)
    {
      Uri uri = request.Uri;
      string hostName = uri.Host;
      string pathAndQuery = uri.LocalPath; // Unfortunately, Uri.PathAndQuery doesn't decode characters like '{' and '}', so we use the Uri.LocalPath property
      try
      {
        DvService service;
        ICollection<EndpointConfiguration> endpoints;
        lock (_serverData.SyncObj)
          endpoints = _serverData.UPnPEndPoints;
        foreach (EndpointConfiguration config in endpoints)
        {
          if (!NetworkHelper.HostNamesEqual(hostName, NetworkHelper.IPAddrToHostName(config.EndPointIPAddress)))
            continue;

          // Common check for supported encodings
          string acceptEncoding = request.Headers.Get("ACCEPT-ENCODING") ?? string.Empty;

          // Handle different HTTP methods here
          if (request.Method == "GET")
          { // GET of descriptions
            if (pathAndQuery.StartsWith(config.DescriptionPathBase))
            {
              string acceptLanguage = request.Headers.Get("ACCEPT-LANGUAGE");
              CultureInfo culture = GetFirstCultureOrDefault(acceptLanguage, CultureInfo.InvariantCulture);

              string description = null;
              DvDevice rootDevice;
              lock (_serverData.SyncObj)
                if (config.RootDeviceDescriptionPathsToRootDevices.TryGetValue(pathAndQuery, out rootDevice))
                  description = rootDevice.BuildRootDeviceDescription(_serverData, config, culture);
                else if (config.SCPDPathsToServices.TryGetValue(pathAndQuery, out service))
                  description = service.BuildSCPDDocument(config, _serverData);
              if (description != null)
              {
                IHttpResponse response = request.CreateResponse(context);
                response.Status = HttpStatusCode.OK;
                response.ContentType = "text/xml; charset=utf-8";
                if (!string.IsNullOrEmpty(acceptLanguage))
                  response.AddHeader("CONTENT-LANGUAGE", culture.ToString());
                using (MemoryStream responseStream = new MemoryStream(UPnPConsts.UTF8_NO_BOM.GetBytes(description)))
                  CompressionHelper.WriteCompressedStream(acceptEncoding, response, responseStream);
                SafeSendResponse(response);
                return;
              }
            }
          }
          else if (request.Method == "POST")
          { // POST of control messages
            if (config.ControlPathsToServices.TryGetValue(pathAndQuery, out service))
            {
              string contentType = request.Headers.Get("CONTENT-TYPE");
              string userAgentStr = request.Headers.Get("USER-AGENT");
              IHttpResponse response = request.CreateResponse(context);
              int minorVersion;
              if (string.IsNullOrEmpty(userAgentStr))
                minorVersion = 0;
              else if (!ParserHelper.ParseUserAgentUPnP1MinorVersion(userAgentStr, out minorVersion))
              {
                response.Status = HttpStatusCode.BadRequest;
                SafeSendResponse(response);
                return;
              }
              string mediaType;
              Encoding encoding;
              if (!EncodingUtils.TryParseContentTypeEncoding(contentType, Encoding.UTF8, out mediaType, out encoding))
                throw new ArgumentException("Unable to parse content type");
              if (mediaType != "text/xml")
              { // As specified in (DevArch), 3.2.1
                response.Status = HttpStatusCode.UnsupportedMediaType;
                SafeSendResponse(response);
                return;
              }
              response.AddHeader("DATE", DateTime.Now.ToUniversalTime().ToString("R"));
              response.AddHeader("SERVER", UPnPConfiguration.UPnPMachineInfoHeader);
              response.AddHeader("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
              string result;
              HttpStatusCode status;
              try
              {
                CallContext callContext = new CallContext(request, context, config);
                status = SOAPHandler.HandleRequest(service, request.Body, encoding, minorVersion >= 1, callContext, out result);
              }
              catch (Exception e)
              {
                UPnPConfiguration.LOGGER.Warn("Action invocation failed", e);
                result = SOAPHandler.CreateFaultDocument(501, "Action failed");
                status = HttpStatusCode.InternalServerError;
              }
              response.Status = status;
              using (MemoryStream responseStream = new MemoryStream(encoding.GetBytes(result)))
                CompressionHelper.WriteCompressedStream(acceptEncoding, response, responseStream);
              SafeSendResponse(response);
              return;
//.........这里部分代码省略.........
开发者ID:chekiI,项目名称:MediaPortal-2,代码行数:101,代码来源:UPnPServer.cs

示例8: HandleHTTPRequest

 protected void HandleHTTPRequest(IHttpClientContext context, IHttpRequest request)
 {
   Uri uri = request.Uri;
   string hostName = uri.Host;
   string pathAndQuery = uri.PathAndQuery;
   try
   {
     // Handle different HTTP methods here
     if (request.Method == "NOTIFY")
     {
       foreach (DeviceConnection connection in _connectedDevices.Values)
       {
         if (!NetworkHelper.HostNamesEqual(hostName,
             NetworkHelper.IPAddrToHostName(connection.GENAClientController.EventNotificationEndpoint.Address)))
           continue;
         if (pathAndQuery == connection.GENAClientController.EventNotificationPath)
         {
           IHttpResponse response = request.CreateResponse(context);
           response.Status = connection.GENAClientController.HandleUnicastEventNotification(request);
           response.Send();
           return;
         }
       }
     }
     else
     {
       context.Respond(HttpHelper.HTTP11, HttpStatusCode.MethodNotAllowed, null);
       return;
     }
     // Url didn't match
     context.Respond(HttpHelper.HTTP11, HttpStatusCode.NotFound, null);
   }
   catch (Exception) // Don't log the exception here - we don't care about not being able to send the return value to the client
   {
     IHttpResponse response = request.CreateResponse(context);
     response.Status = HttpStatusCode.InternalServerError;
     response.Send();
   }
 }
开发者ID:davinx,项目名称:MediaPortal-2,代码行数:39,代码来源:UPnPControlPoint.cs

示例9: ProcessRequest

        void ProcessRequest(IHttpClientContext context, IHttpRequest request)
        {
            LogWriter.Write(this, LogPrio.Trace, "Processing request...");

            IHttpResponse response = request.CreateResponse(context);

            // Load cookies if they exist
            RequestCookies cookies = request.Headers["cookie"] != null
                                         ? new RequestCookies(request.Headers["cookie"])
                                         : new RequestCookies(String.Empty);
            request.SetCookies(cookies);

            // Create a request signature
            HttpRequestSignature signature = new HttpRequestSignature(request);

            // Look for a signature match in our handlers
            HttpRequestHandler foundHandler = null;

            bool doLock = !rwHandlersLock.IsReadLockHeld;
            if (doLock) rwHandlersLock.EnterReadLock();

            try
            {
                for (int i = 0; i < _requestHandlers.Length; i++)
                {
                    HttpRequestHandler handler = _requestHandlers[i];

                    if (signature == handler.Signature)
                    {
                        foundHandler = handler;
                        break;
                    }
                }
            }
            finally { if (doLock) rwHandlersLock.ExitReadLock(); }

            if (foundHandler != null)
                FireRequestCallback(context, request, response, foundHandler);
            else
                FireRequestCallback(context, request, response, _notFoundHandler);

            LogWriter.Write(this, LogPrio.Trace, "...done processing request.");
        }
开发者ID:robincornelius,项目名称:omvviewer-light,代码行数:43,代码来源:HttpListener.cs

示例10: AuthenticateUser

        private bool AuthenticateUser(ITcpChannel channel, IHttpRequest request)
        {
            if (channel.Data["Principal"] != null)
            {
                Thread.CurrentPrincipal = (IPrincipal)channel.Data["Principal"];
                return true;
            }

            try
            {
                var user = AuthenticationService.Authenticate(request);
                if (user == null)
                    return true;

                if (PrincipalFactory != null)
                {
                    var ctx = new PrincipalFactoryContext(request, user);
                    Thread.CurrentPrincipal = PrincipalFactory.Create(ctx);
                    channel.Data["Principal"] = Thread.CurrentPrincipal;
                    return true;
                }

                var roles = user as IUserWithRoles;
                if (roles == null)
                    throw new InvalidOperationException(
                        "You must specify a PrincipalFactory if you do not return a IUserWithRoles from your IAccountService.");

                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(user.Username), roles.RoleNames);
                channel.Data["Principal"] = Thread.CurrentPrincipal;
            }
            catch (HttpException ex)
            {
                var response = request.CreateResponse();
                response.StatusCode = ex.HttpCode;
                response.ReasonPhrase = FirstLine(ex.Message);
                ;
                channel.Send(response);
                return false;
            }

            return true;
        }
开发者ID:ricklxm,项目名称:Griffin.Framework,代码行数:42,代码来源:WebSocketServer.cs


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