本文整理汇总了C#中HttpRequest类的典型用法代码示例。如果您正苦于以下问题:C# HttpRequest类的具体用法?C# HttpRequest怎么用?C# HttpRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpRequest类属于命名空间,在下文中一共展示了HttpRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Get
public HttpResponse Get(HttpRequest request)
{
if (request == null)
throw new ArgumentNullException("request", "HttpRequest is required for GET.");
if (request.Uri == null)
throw new ArgumentNullException("uri", "GET http request requires uri.");
try
{
HttpResponseMessage response = SendAsync(HttpMethod.Get, request).Result;
return new HttpResponse(response);
}
catch (HttpRequestException ex)
{
return new HttpResponse(HttpStatusCode.InternalServerError, ex.Message);
}
catch (AggregateException ex)
{
return new HttpResponse(HttpStatusCode.InternalServerError, ex.InnerException.Message);
}
catch (Exception ex)
{
return new HttpResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
示例2: GetClientIpAddress
/// <summary>
/// Gets the client ip address.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.String.</returns>
public static string GetClientIpAddress(HttpRequest request) {
try{
var userHostAddress = request.UserHostAddress;
if (userHostAddress == "::1") userHostAddress = "127.0.0.1";
// Attempt to parse. If it fails, we catch below and return "0.0.0.0"
// Could use TryParse instead, but I wanted to catch all exceptions
if (userHostAddress != null){
IPAddress.Parse(userHostAddress);
var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(xForwardedFor)) return userHostAddress;
// Get a list of public ip addresses in the X_FORWARDED_FOR variable
var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();
// If we found any, return the last one, otherwise return the user host address
return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
}
} catch (Exception){
// Always return all zeroes for any failure (my calling code expects it)
return "0.0.0.0";
}
return "0.0.0.0";
}
示例3: Main
public static void Main()
{
const SPI.SPI_module spiBus = SPI.SPI_module.SPI3;
const Cpu.Pin chipSelectPin = Stm32F4Discovery.FreePins.PA15;
const Cpu.Pin interruptPin = Stm32F4Discovery.FreePins.PD1;
const string hostname = "stm32f4";
var mac = new byte[] {0x5c, 0x86, 0x4a, 0x00, 0x00, 0xdd};
//Static IP
//Adapter.IPAddress = "10.15.16.50".ToBytes();
//Adapter.Gateway = "10.15.16.1".ToBytes();
//Adapter.DomainNameServer = Adapter.Gateway;
//Adapter.DomainNameServer2 = "8.8.8.8".ToBytes(); // Google DNS Server
//Adapter.SubnetMask = "255.255.255.0".ToBytes();
//Adapter.DhcpDisabled = true;
//Adapter.VerboseDebugging = true;
Adapter.Start(mac, hostname, spiBus, interruptPin, chipSelectPin);
const int minVal = 0;
const int maxVal = 100;
string apiUrl = @"http://www.random.org/integers/?num=1"
+ "&min=" + minVal + "&max=" + maxVal
+ "&col=1&base=10&format=plain&rnd=new";
var request = new HttpRequest(apiUrl);
request.Headers.Add("Accept", "*/*");
HttpResponse response = request.Send();
if (response != null)
Debug.Print("Random number: " + response.Message.Trim());
}
示例4: _GetUrlSubDirectory
private string _GetUrlSubDirectory(HttpRequest httpRequest)
{
if (_getUrlSubDirectory != null)
return _getUrlSubDirectory(httpRequest);
else
return null;
}
示例5: GetClientIPAddress
public static string GetClientIPAddress(HttpRequest req)
{
string szRemoteAddr = req.ServerVariables["REMOTE_ADDR"];
string szXForwardedFor = req.ServerVariables["X_FORWARDED_FOR"];
string szIP = "";
if (szXForwardedFor == null)
{
szIP = szRemoteAddr;
}
else
{
szIP = szXForwardedFor;
if (szIP.IndexOf(",") > 0)
{
string[] arIPs = szIP.Split(',');
foreach (string item in arIPs)
{
if (item != "127.0.0.1")
{
return item;
}
}
}
}
return szIP;
}
示例6: HttpResponse
public HttpResponse(HttpRequest request, HttpHeader headers, Byte[] binaryData, HttpStatusCode statusCode = HttpStatusCode.OK)
{
Request = request;
Headers = headers;
ResponseData = binaryData;
StatusCode = statusCode;
}
示例7: AddContent_WithHttpWebRequestAdapterAndHttpRequest
public void AddContent_WithHttpWebRequestAdapterAndHttpRequest()
{
// Arrange
Mock<IHttpWebRequestAdapter> mockHttpWebRequest = mocks.Create<IHttpWebRequestAdapter>();
HttpRequest request = new HttpRequest()
{
Content = "content",
ContentEncoding = Encoding.UTF8,
ContentType = "application/xml"
};
Stream stream = new MemoryStream();
mockHttpWebRequest.Setup(wr=>wr.GetRequestStream()).Returns(stream);
mockHttpWebRequest.SetupSet(wr => wr.ContentLength = request.ContentLength);
mockHttpWebRequest.SetupSet(wr => wr.ContentType = request.ContentType);
// Act
helper.AddContent(mockHttpWebRequest.Object, request);
// Assert
// Expectations have been met.
}
示例8: HttpClientContext
/// <summary>
/// Initializes a new instance of the <see cref="HttpClientContext"/> class.
/// </summary>
/// <param name="secured">true if the connection is secured (SSL/TLS)</param>
/// <param name="remoteEndPoint">client that connected.</param>
/// <param name="stream">Stream used for communication</param>
/// <param name="clientCertificate">Client security certificate</param>
/// <param name="parserFactory">Used to create a <see cref="IHttpRequestParser"/>.</param>
/// <param name="bufferSize">Size of buffer to use when reading data. Must be at least 4096 bytes.</param>
/// <param name="socket">Client socket</param>
/// <exception cref="SocketException">If <see cref="Socket.BeginReceive(byte[],int,int,SocketFlags,AsyncCallback,object)"/> fails</exception>
/// <exception cref="ArgumentException">Stream must be writable and readable.</exception>
public HttpClientContext(bool secured, IPEndPoint remoteEndPoint, Stream stream,
ClientCertificate clientCertificate, IRequestParserFactory parserFactory, int bufferSize, Socket socket)
{
Check.Require(remoteEndPoint, "remoteEndPoint");
Check.NotEmpty(remoteEndPoint.Address.ToString(), "remoteEndPoint.Address");
Check.Require(stream, "stream");
Check.Require(parserFactory, "parser");
Check.Min(4096, bufferSize, "bufferSize");
Check.Require(socket, "socket");
if (!stream.CanWrite || !stream.CanRead)
throw new ArgumentException("Stream must be writable and readable.");
_bufferSize = bufferSize;
RemoteAddress = remoteEndPoint.Address.ToString();
RemotePort = remoteEndPoint.Port.ToString();
_log = NullLogWriter.Instance;
_parser = parserFactory.CreateParser(_log);
_parser.RequestCompleted += OnRequestCompleted;
_parser.RequestLineReceived += OnRequestLine;
_parser.HeaderReceived += OnHeaderReceived;
_parser.BodyBytesReceived += OnBodyBytesReceived;
_localEndPoint = (IPEndPoint)socket.LocalEndPoint;
HttpRequest request = new HttpRequest();
request._remoteEndPoint = remoteEndPoint;
request.Secure = secured;
_currentRequest = request;
IsSecured = secured;
_stream = stream;
_clientCertificate = clientCertificate;
_buffer = new byte[bufferSize];
}
示例9: LogoutASync
public async Task<bool> LogoutASync()
{
foreach (var file in _deleteFilesBeforeExit)
{
try
{
if (File.Exists(file))
File.Delete(file);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
// We have done our best
}
}
if (_sessionId == null)
return true;
var httpRequest = new HttpRequest();
httpRequest.Parameters.Add("api", "SYNO.API.Auth");
httpRequest.Parameters.Add("version", "2");
httpRequest.Parameters.Add("method", "Logout");
httpRequest.Parameters.Add("session", "SurveillanceStation");
httpRequest.Parameters.Add("_sid", _sessionId);
await httpRequest.GetASync(_url + "auth.cgi", 200); // There is no data coming back, just continue after some time
return true;
}
示例10: Info
public static HttpContent Info(HttpRequest request)
{
string data = "";
if (request.Data != null)
{
data = StringHelper.GetString(request.Data);
}
var baseContent = new Dictionary<string, HttpContent>() {};
// get connections
lock (request.Server.Connections)
{
var totalConnections = request.Server.Connections.Count.ToString();
var connections = "";
foreach (var connection in request.Server.Connections)
{
if (!connection.Stopped)
{
var ip = ((IPEndPoint)connection.Socket.Client.RemoteEndPoint).Address.ToString();
var port = ((IPEndPoint)connection.Socket.Client.RemoteEndPoint).Port.ToString();
connections += ip + ":" + port + "\n";
}
else
{
connections += "timed out\n";
}
}
baseContent.Add("TotalConnections", new HttpContent(totalConnections));
baseContent.Add("Connections", new HttpContent(connections));
}
// get sessions
// TODO: finish
lock (request.Server.Sessions)
{
var totalSessions = request.Server.Sessions.Count.ToString();
var sessions = "";
foreach (var session in request.Server.Sessions)
{
sessions += session.Key + " - " + session.Value.CreationDate.ToString() + "\n";
}
baseContent.Add("TotalSessions", new HttpContent(totalSessions));
baseContent.Add("Sessions", new HttpContent(sessions));
}
var currentSession = "";
currentSession += "ID: " + request.Session.ID + "\n";
currentSession += "Created: " + request.Session.CreationDate.ToString() + "\n";
currentSession += "ExpiryDate: " + request.Session.ExpiryDate.ToString() + "\n";
baseContent.Add("Session", new HttpContent(currentSession));
return HttpContent.Read(request.Server, "sar.Http.Views.Debug.Info.html", baseContent);
}
示例11: Handle
public void Handle(HttpRequest req, HttpResponse resp, JsonRpcHandler jsonRpcHandler)
{
if(req.HttpMethod != "POST")
{
resp.Status = "405 Method Not Allowed";
return;
}
if(!req.ContentType.StartsWith("application/json"))
{
resp.Status = "415 Unsupported Media Type";
return;
}
JToken json;
try
{
json = JToken.ReadFrom(new JsonTextReader(req.Content));
}
catch(Exception e)
{
resp.Status = "400 Bad Request";
resp.ContentType = "text/plain";
resp.Content.WriteLine(e);
return;
}
resp.Status = "200 OK";
resp.ContentType = "application/json";
using(var jsonWriter = new JsonTextWriter(resp.Content))
{
new JsonSerializer().Serialize(jsonWriter, jsonRpcHandler.Handle(json));
}
}
示例12: HandlerApplication_Error
/// <param name="request">The request from the GlobalAsax is behaves differently!</param>
public static void HandlerApplication_Error(HttpRequest request, HttpContext context, bool isWebRequest)
{
if (Navigator.Manager == null || !Navigator.Manager.Initialized)
return;
Exception ex = CleanException(context.Server.GetLastError());
context.Server.ClearError();
context.Response.StatusCode = GetHttpError(ex);
context.Response.TrySkipIisCustomErrors = true;
HandleErrorInfo hei = new HandleErrorInfo(ex, "Global.asax", "Application_Error");
if (LogException != null)
LogException(hei);
if (isWebRequest)
{
HttpContextBase contextBase = context.Request.RequestContext.HttpContext;
IController controller = new ErrorController { Result = GetResult(contextBase, hei) };
var rd = new RouteData
{
Values=
{
{ "Controller", "Error"},
{ "Action", "Error"}
}
};
controller.Execute(new RequestContext(contextBase, rd));
}
}
示例13: GetBlobPath
private static string GetBlobPath(HttpRequest request)
{
string hostName = request.Url.DnsSafeHost;
if (hostName == "localdev")
{
hostName = "www.protonit.net";
}
string containerName = hostName.Replace('.', '-');
string currServingFolder = "";
try
{
// "/2013-03-20_08-27-28";
CloudBlobClient publicClient = new CloudBlobClient("http://caloom.blob.core.windows.net/");
string currServingPath = containerName + "/" + RenderWebSupport.CurrentToServeFileName;
var currBlob = publicClient.GetBlockBlobReference(currServingPath);
string currServingData = currBlob.DownloadText();
string[] currServeArr = currServingData.Split(':');
string currActiveFolder = currServeArr[0];
var currOwner = VirtualOwner.FigureOwner(currServeArr[1]);
InformationContext.Current.Owner = currOwner;
currServingFolder = "/" + currActiveFolder;
}
catch
{
}
return containerName + currServingFolder + request.Path;
}
示例14: Get
static void Get(string url)
{
HttpRequest request = new HttpRequest();
request.Cookies = new CookieDictionary();
HttpResponse response = request.Get(url);
Console.WriteLine(response.ToString());
}
示例15: BaseAppelRequstHandler
public BaseAppelRequstHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, string VersionHeader)
{
this.Request = Request;
this.Response = Response;
this.Prefix = Prefix;
this.VersionHeader = VersionHeader;
}