本文整理汇总了C#中HttpRequest类的典型用法代码示例。如果您正苦于以下问题:C# HttpRequest类的具体用法?C# HttpRequest怎么用?C# HttpRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpRequest类属于命名空间,在下文中一共展示了HttpRequest类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
开发者ID:kbolay,项目名称:Bolay.Elastic,代码行数:26,代码来源:HttpLayer.cs
示例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";
}
开发者ID:NemediDev,项目名称:Intercom.Heath,代码行数:31,代码来源:WebHelper.cs
示例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());
}
开发者ID:dario-l,项目名称:kodfilemon.blogspot.com,代码行数:33,代码来源:Program.cs
示例4: _GetUrlSubDirectory
private string _GetUrlSubDirectory(HttpRequest httpRequest)
{
if (_getUrlSubDirectory != null)
return _getUrlSubDirectory(httpRequest);
else
return null;
}
开发者ID:labeuze,项目名称:source,代码行数:7,代码来源:UrlCache.cs
示例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;
}
开发者ID:huanlin,项目名称:YetAnotherLibrary,代码行数:28,代码来源:WebHelper.cs
示例6: HttpResponse
public HttpResponse(HttpRequest request, HttpHeader headers, Byte[] binaryData, HttpStatusCode statusCode = HttpStatusCode.OK)
{
Request = request;
Headers = headers;
ResponseData = binaryData;
StatusCode = statusCode;
}
开发者ID:keep3r,项目名称:Sonarr,代码行数:7,代码来源:HttpResponse.cs
示例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.
}
开发者ID:jimgolfgti,项目名称:esendex-dotnet-sdk,代码行数:25,代码来源:HttpRequestHelperTests.cs
示例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];
}
开发者ID:BGCX261,项目名称:zma-svn-to-git,代码行数:47,代码来源:HttpClientContext.cs
示例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;
}
开发者ID:SynoCam,项目名称:synocam,代码行数:31,代码来源:ApiConnector.cs
示例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);
}
开发者ID:cwillison94,项目名称:sar-tool,代码行数:60,代码来源:DebugController.cs
示例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));
}
}
开发者ID:gimmi,项目名称:jsonrpchandler,代码行数:31,代码来源:JsonRpcHttpHandler.cs
示例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));
}
}
开发者ID:nuub666,项目名称:framework,代码行数:35,代码来源:SignumExceptionHandlerAttribute.cs
示例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;
}
开发者ID:kallex,项目名称:Caloom,代码行数:28,代码来源:AnonymousBlobStorageHandler.cs
示例14: Get
static void Get(string url)
{
HttpRequest request = new HttpRequest();
request.Cookies = new CookieDictionary();
HttpResponse response = request.Get(url);
Console.WriteLine(response.ToString());
}
开发者ID:maltyyev,项目名称:FAMILab,代码行数:7,代码来源:Program.cs
示例15: BaseAppelRequstHandler
public BaseAppelRequstHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, string VersionHeader)
{
this.Request = Request;
this.Response = Response;
this.Prefix = Prefix;
this.VersionHeader = VersionHeader;
}
开发者ID:TheHandsomeCoder,项目名称:SOFT512RestAPI,代码行数:7,代码来源:BaseAppelRequstHandler.cs
示例16: IsStaticResource
/// <summary>
/// Returns true if the requested resource is one of the typical resources that needn't be processed by the cms engine.
/// </summary>
/// <param name="request">HTTP Request</param>
/// <returns>True if the request targets a static resource file.</returns>
/// <remarks>
/// These are the file extensions considered to be static resources:
/// .css
/// .gif
/// .png
/// .jpg
/// .jpeg
/// .js
/// .axd
/// .ashx
/// </remarks>
public static bool IsStaticResource(HttpRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
string path = request.Path;
string extension = VirtualPathUtility.GetExtension(path);
if (extension == null) return false;
switch (extension.ToLower())
{
case ".axd":
case ".ashx":
case ".bmp":
case ".css":
case ".gif":
case ".htm":
case ".html":
case ".ico":
case ".jpeg":
case ".jpg":
case ".js":
case ".png":
case ".rar":
case ".zip":
return true;
}
return false;
}
开发者ID:Xamarui,项目名称:mvcforum,代码行数:47,代码来源:AppHelpers.cs
示例17: GetResponse
public HttpResponse GetResponse(HttpRequest request)
{
var url = request.Url;
if (request.QueryString != null && request.QueryString.Any())
{
var encodedQueryString = ToQueryString(request.QueryString);
url = string.Format("{0}?{1}", url, encodedQueryString);
}
var key = GetRequestKey(request.Method, url, request.Headers, request.Body);
if (stubbedRequests.ContainsKey(key) == false)
{
throw new ArgumentException(
"\n\n----------\n\n" +
"No stub found\n" +
"=============\n\n" +
key +
"\n\n\n" +
"Known stubs" +
"\n============\n\n" +
string.Join("\n\n-----\n\n", stubbedRequests.Keys.ToArray()) +
"\n\n"
);
}
var stub = stubbedRequests[key];
return new HttpResponse {
Code = stub.ResponseCode,
Headers = new Dictionary<string, string>(),
Body = stub.ResponseBody,
};
}
开发者ID:cronofy,项目名称:cronofy-csharp,代码行数:35,代码来源:StubHttpClient.cs
示例18: IntializeRequestInfo
protected override void IntializeRequestInfo(HttpRequest httpRequest)
{
// base method
base.IntializeRequestInfo(httpRequest);
AjaxRequest.CustomHeaders = ExtractAJAXHeader(_currentContext.Request);
AJAXInfo _AJAXInfo = GetAJAXInfo(_currentContext.Request.Params);
// validate url
if (string.IsNullOrEmpty(RequestInfo.RequestUrl))
{
LastErrorMessage = "Invalid AJAX headers.";
LastStatus = LastStatus.Error;
return;
}
AjaxRequest.Username = _AJAXInfo.UserName;
AjaxRequest.Password = _AJAXInfo.Password;
RequestInfo.SetContentType(GetContentTypeInCollection(AjaxRequest.CustomHeaders, _DefaultContentType));
RequestInfo.RedirectedFrom = GetRequestReferer(
AjaxRequest.CustomHeaders,
_currentContext.Request,
Consts.BackEndConenction.ASProxyProjectUrl);
}
开发者ID:EdiCarlos,项目名称:MyPractices,代码行数:25,代码来源:AjaxEngine.cs
示例19: ProxyRequest
protected virtual HttpWebResponse ProxyRequest(HttpRequest source)
{
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(Url + "?" + source.QueryString.ToString());
Req.KeepAlive = false;
Req.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
Req.UseDefaultCredentials = true;
// *** Set properties
Req.Timeout = 60000;
Req.UserAgent = source.UserAgent;
Req.Method = source.HttpMethod;
Req.ContentType = source.ContentType;
Req.Headers.Add("Impersonate", source.LogonUserIdentity.Name);
foreach (string H in ReqHeaders)
{
var V = source.Headers[H];
if (V != null)
Req.Headers.Add(H, V);
}
if (Req.Method == "POST")
using (var ReqStream = Req.GetRequestStream())
{
source.InputStream.CopyTo(ReqStream);
}
return Req.GetResponse() as HttpWebResponse;
}
开发者ID:randomdima,项目名称:WebRPC,代码行数:28,代码来源:RPCProxy.cs
示例20: GetUrlPathResult
public UrlCachePathResult GetUrlPathResult(HttpRequest httpRequest, string subDirectory = null)
{
string subPath = GetUrlSubPath(httpRequest);
if (subDirectory != null)
subPath = zPath.Combine(subDirectory, subPath);
return new UrlCachePathResult { Path = zPath.Combine(_cacheDirectory, subPath), SubPath = subPath };
}
开发者ID:labeuze,项目名称:source,代码行数:7,代码来源:UrlCache.cs
注:本文中的HttpRequest类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论