本文整理汇总了C#中RequestMethod.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# RequestMethod.ToString方法的具体用法?C# RequestMethod.ToString怎么用?C# RequestMethod.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RequestMethod
的用法示例。
在下文中一共展示了RequestMethod.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Map
public static Method Map(RequestMethod method)
{
Method mthd;
Enum.TryParse(method.ToString().ToUpperInvariant(), out mthd);
return mthd;
}
示例2: HtmlForm
public HtmlForm(RequestMethod method, string action, IDictionary<string, string> errors = null)
: base("form", null)
{
SetAttribut("name", "form");
SetAttribut("method", method.ToString());
SetAttribut("action", action);
SetAttribut("onsubmit", "return FormIsValid()");
_errors = errors;
}
示例3: GetWebRequest
/// <summary>
/// 网页请求
/// </summary>
/// <param name="postUrl">URL</param>
/// <param name="requestMethod">请求方法</param>
/// <param name="param">请求参数</param>
/// <param name="encoding">编码</param>
/// <param name="headers">头部</param>
/// <returns></returns>
public static string GetWebRequest(string postUrl, RequestMethod requestMethod = RequestMethod.Get ,string param = null, Encoding encoding = null, WebHeaderCollection headers = null)
{
postUrl = postUrl.Trim();
if (postUrl.IndexOf("http://") != 0)
{
postUrl = "http://" + postUrl;
}
string ret = string.Empty;
HttpWebResponse response;
StackTrace st = new StackTrace(true);
try
{
if (encoding == null)
{
encoding = Encoding.UTF8;
}
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(postUrl));
if (headers != null) webRequest.Headers = headers;
webRequest.Method = requestMethod.ToString();
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.UserAgent = "User-Agent";
webRequest.KeepAlive = true;
if (param != null && requestMethod == RequestMethod.Post)
{
byte[] paramByte = encoding.GetBytes(param);
webRequest.ContentLength = paramByte.Length;
var webStream = webRequest.GetRequestStream();
webStream.Write(paramByte, 0, paramByte.Length);
webStream.Close();
}
response = (HttpWebResponse)webRequest.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), encoding);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
}
catch (Exception)
{
throw;
}
return ret;
}
示例4: RequestStreamingAPI
/// <summary>
/// RequestStreamAPI implementation
/// </summary>
/// <param name="uri">full uri</param>
/// <param name="method">using method for HTTP negotiation</param>
/// <param name="param">parameters</param>
/// <returns>Callback stream</returns>
public override sealed Stream RequestStreamingAPI(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, out HttpWebRequest request)
{
if (String.IsNullOrEmpty(uri))
throw new ArgumentNullException(uri);
else if (uri.Length < 5)
throw new ArgumentException("uri is too short.");
string target = uri;
if (String.IsNullOrEmpty(Token) || String.IsNullOrEmpty(Secret))
{
throw new WebException("OAuth Not Validated", WebExceptionStatus.ProtocolError);
}
var reg = GetHeader(target, method, param);
try
{
var ps = JoinParamAsUrl(param);
System.Diagnostics.Debug.WriteLine("streaming params:" + ps);
byte[] body = null;
if (!String.IsNullOrWhiteSpace(ps))
{
if (method == RequestMethod.GET)
target += "?" + ps;
if (method == RequestMethod.POST)
body = Encoding.ASCII.GetBytes(ps);
}
request = Http.CreateRequest(new Uri(target), method.ToString(), contentType: "application/x-www-form-urlencoded");
request.Headers.Add("Authorization", "OAuth " + reg);
request.Timeout = 8000;
request.AutomaticDecompression = DecompressionMethods.None; // due to delaying streaming receiving.
var ret = Http.WebConnect<Stream>(req: request, responseconv: Http.ResponseConverters.GetStream, senddata: body);
if (ret.Succeeded)
{
return ret.Data;
}
else
{
if (ret.Data != null)
ret.Data.Close();
if (ret.ThrownException != null)
throw ret.ThrownException;
else
throw new WebException();
}
}
catch (WebException)
{
throw;
}
catch (IOException)
{
throw;
}
}
示例5: RequestAPI
/// <summary>
/// RequestAPI implementation
/// </summary>
/// <param name="uri">full uri</param>
/// <param name="method">using method for HTTP negotiation</param>
/// <param name="param">additional parameters</param>
/// <param name="request">used request</param>
/// <returns>XML documents</returns>
public override sealed XDocument RequestAPI(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, out HttpWebRequest request)
{
// validate arguments
if (String.IsNullOrEmpty(uri))
throw new ArgumentNullException(uri);
else if (uri.Length < 5)
throw new ArgumentException("uri is too short.");
string target = uri;
// detection return type of api
var docType = DocumentTypes.Invalid;
if (target.EndsWith("xml"))
docType = DocumentTypes.Xml;
else if (target.EndsWith("json"))
docType = DocumentTypes.Json;
else
throw new ArgumentException("format can't identify. uriPartial is must ends with .xml or .json.");
// pre-validation authentication
if (String.IsNullOrEmpty(Token) || String.IsNullOrEmpty(Secret))
{
throw new WebException("OAuth Not Validated", WebExceptionStatus.ProtocolError);
}
var reg = GetHeader(target, method, param);
try
{
var ps = JoinParamAsUrl(param);
byte[] body = null;
if (!String.IsNullOrWhiteSpace(ps))
{
if (method == RequestMethod.GET)
target += "?" + ps;
if (method == RequestMethod.POST)
body = Encoding.ASCII.GetBytes(ps);
}
request = Http.CreateRequest(new Uri(target), method.ToString(), contentType: "application/x-www-form-urlencoded");
request.Headers.Add("Authorization", "OAuth " + reg);
var ret = Http.WebConnect<XDocument>(request,
responseconv: new Http.ResponseConverter<XDocument>((res) =>
{
switch (docType)
{
case DocumentTypes.Xml:
return XDocumentGenerator(res);
case DocumentTypes.Json:
return XDocumentGenerator(res, (s) => JsonReaderWriterFactory.CreateJsonReader(s, XmlDictionaryReaderQuotas.Max));
default:
throw new NotSupportedException("Invalid format.");
}
}), senddata: body);
if (ret.Succeeded && ret.Data != null)
{
return ret.Data;
}
else
{
if (ret.ThrownException != null)
throw ret.ThrownException;
else
throw new WebException();
}
}
catch (WebException)
{
throw;
}
catch (XmlException)
{
throw;
}
catch (IOException)
{
throw;
}
}
示例6: GenerateSignatureBase
/// <summary>
/// Generate the signature base that is used to produce the signature
/// </summary>
/// <param name="url">The full URL that needs to be signed including its non OAuth URL parameters.</param>
/// <param name="consumerKey">The consumer key.</param>
/// <param name="token">The token, if available. If not available pass null or an empty string.</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string.</param>
/// <param name="verifier">The callback verifier, if available. If not available pass null or an empty string.</param>
/// <param name="httpMethod">The HTTP method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The signature type. To use the default values use <see cref="SignatureType">SignatureType</see>.</param>
/// <returns>The signature base.</returns>
private string GenerateSignatureBase (Uri url, string consumerKey, string token, string tokenSecret, string verifier,
RequestMethod method, TimeSpan timeStamp, string nonce, SignatureType signatureType, string callbackUrl,
out string normalizedUrl,
out List<IQueryParameter<string>> parameters)
{
log.LogDebug ("Generating signature base for OAuth request.");
token = token ?? string.Empty;
tokenSecret = tokenSecret ?? string.Empty;
verifier = verifier ?? String.Empty;
if (consumerKey == null) throw new ArgumentNullException ("consumerKey");
log.LogDebug ("URL: {0}", url.Query);
var signatureString = string.Empty;
switch (signatureType) {
case SignatureType.HMACSHA1:
signatureString = "HMAC-SHA1";
break;
case SignatureType.RSASHA1:
signatureString = "RSA-SHA1";
break;
case SignatureType.PLAINTEXT:
signatureString = SignatureType.PLAINTEXT.ToString ();
break;
}
parameters = GetQueryParameters (url.Query).Concat (new List<IQueryParameter<string>> {
new QueryParameter<string> (OAuthVersionKey, OAuthVersion, s => string.IsNullOrEmpty (s)),
new QueryParameter<string> (OAuthTimestampKey, ((long)timeStamp.TotalSeconds).ToString (), s => string.IsNullOrEmpty (s)),
new QueryParameter<string> (OAuthSignatureMethodKey, signatureString, s => string.IsNullOrEmpty (s)),
new QueryParameter<string> (OAuthNonceKey, nonce, s => string.IsNullOrEmpty (s)),
new QueryParameter<string> (OAuthConsumerKeyKey, consumerKey, s => string.IsNullOrEmpty (s))
}).ToList ();
if (!string.IsNullOrEmpty (token)) parameters.Add (new QueryParameter<string> (OAuthTokenKey, token, s => string.IsNullOrEmpty (s)));
if (!string.IsNullOrEmpty (verifier)) parameters.Add (new QueryParameter<string> (OAuthVerifierKey, verifier, s => string.IsNullOrEmpty (s)));
if (!string.IsNullOrEmpty (callbackUrl)) parameters.Add (new QueryParameter<string> (OAuthCallbackKey, UrlEncode (callbackUrl), s => string.IsNullOrEmpty (s)));
log.LogDebug ("Normalizing URL for signature.");
normalizedUrl = string.Format ("{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) normalizedUrl += ":" + url.Port;
normalizedUrl += url.AbsolutePath;
log.LogDebug ("Generated normalized URL: {0}", normalizedUrl);
log.LogDebug ("Normalizing request parameters.");
parameters.Sort ();
string normalizedRequestParameters = parameters.NormalizeRequestParameters ();
log.LogDebug ("Normalized request parameters {0}.", normalizedRequestParameters);
log.LogDebug ("Generating signature base from normalized URL and request parameters.");
var signatureBase = new StringBuilder ();
signatureBase.AppendFormat("{0}&", method.ToString ());
signatureBase.AppendFormat("{0}&", UrlEncode (normalizedUrl));
signatureBase.AppendFormat("{0}", UrlEncode (normalizedRequestParameters));
log.LogDebug ("Signature base: {0}", signatureBase.ToString ());
return signatureBase.ToString ();
}
示例7: PrepareRequest
private HttpWebRequest PrepareRequest(Uri uri, RequestMethod method, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AllowAutoRedirect = false;
request.Method = method.ToString().ToUpper();
if (method == RequestMethod.Post)
{
request.ContentType = contentType;
}
if (!_isRunningOnMono)
{
request.AutomaticDecompression = DecompressionMethods.GZip |
DecompressionMethods.Deflate;
}
else
{
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
}
request.ServicePoint.Expect100Continue = false;
request.Expect = "";
request.UserAgent = _userAgent;
request.CookieContainer = new CookieContainer();
if (_cookies != null && _cookies.Count > 0)
{
request.CookieContainer = _cookies;
}
return request;
}
示例8: GetResponseFromWattRequest
private HttpWebResponse GetResponseFromWattRequest(Uri requestUrl, RequestMethod method, string postData = "")
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
httpWebRequest.CookieContainer = _cookieJar;
httpWebRequest.UserAgent = "CSharp HTTP Sample";
httpWebRequest.KeepAlive = true;
httpWebRequest.Headers.Set("Pragma", "no-cache");
httpWebRequest.Timeout = 300000;
httpWebRequest.Method = method.ToString();
if (method == RequestMethod.Post)
{
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(postData);
httpWebRequest.ContentLength = bytes.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
return (HttpWebResponse)httpWebRequest.GetResponse();
}
catch
{
return null;
}
}
示例9: CreateHttpWebRequest
/// <summary>
///
/// </summary>
/// <param name="requestMethod"></param>
/// <param name="url"></param>
/// <param name="authorisationToken"></param>
/// <param name="navigationPage"></param>
/// <param name="navigationPageSize"></param>
/// <returns></returns>
private static HttpWebRequest CreateHttpWebRequest(RequestMethod requestMethod, string url, string authorisationToken, int? navigationPage = null, int? navigationPageSize = null, string methodOverride = null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/xml";
request.Method = requestMethod.ToString();
request.KeepAlive = false;
request.Accept = "application/xml";
request.Headers.Add("Authorization", authorisationToken);
if (navigationPage.HasValue)
{
request.Headers.Add("navigationPage", navigationPage.Value.ToString());
}
if (navigationPageSize.HasValue)
{
request.Headers.Add("navigationPageSize", navigationPageSize.Value.ToString());
}
if (!String.IsNullOrWhiteSpace(methodOverride))
{
request.Headers.Add("X-HTTP-Method-Override", methodOverride.Trim());
}
return request;
}
示例10: CreateRequest
/// <summary>
/// creates HttpWebRequest including IDataBase data, request params, query filter and granularity
/// </summary>
/// <param name="requestMethod">RequestMethod</param>
/// <param name="model">Ataxo.SlimAPIClient.Entities.Constants.Model</param>
/// <param name="requestParams">params od model usually used for updating</param>
/// <param name="queryItems">filter params</param>
/// <param name="granularity">Granularity</param>
/// <returns></returns>
protected HttpWebRequest CreateRequest(RequestMethod requestMethod, string model, string additional_concretization = null, IDictionary<string, object> requestParams = null, IEnumerable<QueryItem> queryItems = null, Granularity granularity = null)
{
string url = ConstrucUrl(PropertiesData, model, additional_concretization, queryItems, granularity);
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Headers["Api-Token"] = PropertiesData.AccessToken;
request.Method = requestMethod.ToString().ToUpper();
return request;
}
示例11: ConvertRequestMethod
protected Method ConvertRequestMethod(RequestMethod method)
{
if (method == RequestMethod.Get)
return Method.GET;
else if (method == RequestMethod.Post)
return Method.POST;
else
throw new NotSupportedException(
string.Format("The request method of {0} is not supported", method.ToString()));
}
示例12: WebRequest
/// <summary>
/// Web Request Wrapper
/// </summary>
/// <param name="method">Http Method</param>
/// <param name="url">Full url to the web resource</param>
/// <param name="postData">Data to post in querystring format</param>
/// <returns>The web server response.</returns>
public string WebRequest(RequestMethod method, string url, string postData)
{
string responseData = "";
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
//webRequest.UserAgent = "Identify your application please.";
//webRequest.Timeout = 20000;
if (method == RequestMethod.POST || method == RequestMethod.DELETE)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
using (StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
try
{
requestWriter.Write(postData);
}
finally
{
requestWriter.Close();
}
}
}
responseData = WebResponseGet(webRequest);
}
webRequest = null;
return responseData;
}
示例13: OAuthWebRequest
/// <summary>
/// Submit a web request using oAuth.
/// </summary>
/// <param name="method">GET or POST</param>
/// <param name="url">The full url, including the querystring.</param>
/// <param name="postData">Data to post (querystring format)</param>
/// <returns>The web server response.</returns>
public string OAuthWebRequest(RequestMethod method, string url, string postData)
{
string outUrl = "";
string querystring = "";
string ret = "";
//Setup postData for signing.
//Add the postData to the querystring.
if (method == RequestMethod.POST || method == RequestMethod.DELETE)
{
if (postData.Length > 0)
{
//Decode the parameters and re-encode using the oAuth UrlEncode method.
NameValueCollection qs = HttpUtility.ParseQueryString(postData);
postData = "";
foreach (string key in qs.AllKeys)
{
if (postData.Length > 0)
{
postData += "&";
}
qs[key] = HttpUtility.UrlDecode(qs[key]);
qs[key] = UrlEncode(qs[key]);
postData += key + "=" + qs[key];
}
if (url.IndexOf("?", StringComparison.Ordinal) > 0)
{
url += "&";
}
else
{
url += "?";
}
url += postData;
}
}
var uri = new Uri(url);
string nonce = GenerateNonce();
string timeStamp = GenerateTimeStamp();
//Generate Signature
string sig = GenerateSignature(uri,
ConsumerKey,
ConsumerSecret,
Token,
TokenSecret,
CallBackUrl,
OAuthVerifier,
method.ToString(),
timeStamp,
nonce,
out outUrl,
out querystring);
querystring += "&oauth_signature=" + UrlEncode(sig);
//Convert the querystring to postData
if (method == RequestMethod.POST || method == RequestMethod.DELETE)
{
postData = querystring;
querystring = "";
}
if (querystring.Length > 0)
{
outUrl += "?";
}
ret = WebRequest(method, outUrl + querystring, postData);
return ret;
}
示例14: GetHeader
/// <summary>
/// Get Authentication header text
/// </summary>
protected string GetHeader(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, string pin = null, bool gettingRequestToken = false)
{
var oap = GetOAuthParams(
ConsumerKey, Token,
GetTimestamp(), GetNonce(),
SignatureMethod, pin, gettingRequestToken);
var sig = GetSignature(
new Uri(uri), ConsumerSecret, Secret,
JoinParamAsUrl(param == null ? oap : oap.Concat(param)),
SignatureMethod, method.ToString());
return JoinParamAsHeader(
oap.Concat(new[] { new KeyValuePair<string, string>(SignatureKey, sig) }).ToArray());
}
示例15: CreateUrl
private string CreateUrl(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, string pin)
{
StringBuilder sb = new StringBuilder();
param = AddOAuthParams(
param,
ConsumerKey, Token,
GetTimestamp(), GetNonce(),
SignatureType, pin);
string strp = JoinParam(param);
string sig = GetSignature(
new Uri(uri),
ConsumerSecret, Secret,
strp, SignatureType, method.ToString());
List<KeyValuePair<string, string>> np = new List<KeyValuePair<string, string>>();
if (param != null)
np.AddRange(param);
np.Add(new KeyValuePair<string, string>(SignatureKey, sig));
return uri + "?" + JoinParam(np);
}