本文整理汇总了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");
}
示例2: ControllerModuleTest
public ControllerModuleTest()
{
_controller = new TestController();
_request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
_context = new HttpResponseContext();
_response = _request.CreateResponse(_context);
_module = new ControllerModule();
}
示例3: RequestControllerTest
public RequestControllerTest()
{
_controller = new MyController();
_request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
_stream = new MyStream();
_context = new HttpResponseContext();
_response = _request.CreateResponse(_context);
}
示例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();
}
示例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))
//.........这里部分代码省略.........
示例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);
}
}
}
示例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;
//.........这里部分代码省略.........
示例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();
}
}
示例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.");
}
示例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;
}