本文整理汇总了C#中System.Net.NetworkCredential.GetCredential方法的典型用法代码示例。如果您正苦于以下问题:C# NetworkCredential.GetCredential方法的具体用法?C# NetworkCredential.GetCredential怎么用?C# NetworkCredential.GetCredential使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.NetworkCredential
的用法示例。
在下文中一共展示了NetworkCredential.GetCredential方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendMail
public bool SendMail()
{
MailMessage message = new MailMessage(FromAddress, ToAddress, Subject, MessageText);
SetServer();
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = EnableSSL;
client.Port = Port;
if (Encrypted)
{
}
message.CC.Add(CC);
message.Bcc.Add(BCC);
client.Host = _SMTPServer;
client.UseDefaultCredentials = false;
NetworkCredential credential = new NetworkCredential(_SMTPUsername, _SMTPPassword);
credential.GetCredential(client.Host, Port, AuthenticationType);
client.Credentials = credential;
message.ReplyTo = message.From;
try
{
client.Send(message);
}
catch(Exception err)
{
MMDBExceptionHandler.HandleException(err);
throw(err);
}
return true;
}
示例2: CheckDefaults
void CheckDefaults (NetworkCredential nc)
{
Assert.AreSame (String.Empty, nc.Domain, "Domain");
Assert.AreSame (String.Empty, nc.Password, "Password");
Assert.AreSame (String.Empty, nc.UserName, "UserName");
Assert.AreSame (nc, nc.GetCredential (null, null), "GetCredential");
}
示例3: CheckCustom
void CheckCustom (NetworkCredential nc)
{
Assert.AreEqual ("dom", nc.Domain, "Domain");
Assert.AreEqual ("********", nc.Password, "Password");
Assert.AreEqual ("user", nc.UserName, "UserName");
Assert.AreSame (nc, nc.GetCredential (new Uri ("http://www.mono-project.com"), "basic"), "GetCredential");
}
示例4: Main
private static void Main()
{
const string smtpHost = "smtp.socketlabs.com";
const int smtpPort = 2525; // standard is port 25 but that is blocked by many ISP's
const string smtpUserName = "YOUR-SMTP-USER-NAME";
const string smtpPassword = "YOUR-SMTP-API-PASSWORD";
var creds = new NetworkCredential(smtpUserName, smtpPassword);
var auth = creds.GetCredential(smtpHost, smtpPort, "Basic");
using (var msg = new MailMessage())
using (var smtp = new SmtpClient())
{
// ** can be set in config **
// you can skip this set by setting your credentials in the web.config or app.config
// http://msdn.microsoft.com/en-us/library/w355a94k.aspx
smtp.Host = smtpHost;
smtp.Port = smtpPort;
smtp.Credentials = auth;
// ** can be set in config **
msg.From = new MailAddress("[email protected]");
msg.To.Add("[email protected]");
msg.Subject = "Using the SMTP client with SocketLabs.";
msg.Body = "<h1>Hello</h1><p>How are you doing today?</p>";
msg.IsBodyHtml = true;
smtp.Send(msg);
}
Console.WriteLine("Email Sent");
Console.Read();
}
示例5: Send
//邮件发送
public void Send()
{
try
{
if (mMailMessage != null)
{
mSmtpClient = new SmtpClient();
//mSmtpClient.Host = "smtp." + mMailMessage.From.Host;
mSmtpClient.Host = this.mSenderServerHost;
mSmtpClient.Port = this.mSenderPort;
mSmtpClient.UseDefaultCredentials = false;
mSmtpClient.EnableSsl = this.mEnableSsl;
if (this.mEnablePwdAuthentication)
{
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
//mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
//NTLM: Secure Password Authentication in Microsoft Outlook Express
mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
}
else
{
mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
}
mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mSmtpClient.Send(mMailMessage);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
示例6: GetSmtpClient
private SmtpClient GetSmtpClient(EmailServerSettings emailServerSettings)
{
if(emailServerSettings == null)
{
emailServerSettings = this.EmailServerSettings;
}
if(emailServerSettings == null)
{
return new SmtpClient();
}
else
{
int port = emailServerSettings.Port.GetValueOrDefault(25);
var smtpClient = new SmtpClient(emailServerSettings.Host, port);
if (!string.IsNullOrEmpty(emailServerSettings.UserName))
{
var credential = new NetworkCredential(emailServerSettings.UserName, emailServerSettings.Password);
credential.GetCredential(smtpClient.Host, port, "Basic");
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credential;
}
return smtpClient;
}
}
示例7: NewPostRequest
/// <summary>
/// Sends a post request to the sever
/// </summary>
/// <returns></returns>
public string NewPostRequest(string method, IDictionary<string, string> keyValues, NetworkCredential credentials)
{
Uri address = new Uri(_baseUrl + method);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
if (credentials != null)
{
request.Credentials = credentials.GetCredential(address, "Windows");
request.PreAuthenticate = true;
}
StringBuilder data = new StringBuilder();
bool first = true;
foreach (string key in keyValues.Keys)
{
if (!first)
data.Append("&");
data.Append(key + "=" + HttpUtility.UrlEncode(keyValues[key]));
first = false;
}
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
return reader.ReadToEnd();
}
}
示例8: Send
public static MailState Send(MailInfo mailInfo)
{
MailConfig mailConfig = SiteConfig.MailConfig;
MailState mailcode = ValidInfo(mailInfo, mailConfig);
if (mailcode == MailState.None)
{
SmtpClient client = new SmtpClient();
MailMessage mailMessage = GetMailMessage(mailInfo, mailConfig);
try
{
try
{
client.Host = mailConfig.MailServer;
client.Port = mailConfig.Port;
NetworkCredential credential = new NetworkCredential(mailConfig.MailServerUserName, mailConfig.MailServerPassWord);
string authenticationType = string.Empty;
switch (mailConfig.AuthenticationType)
{
case AuthenticationType.None:
client.UseDefaultCredentials = false;
break;
case AuthenticationType.Basic:
client.UseDefaultCredentials = true;
authenticationType = "Basic";
break;
case AuthenticationType.Ntlm:
authenticationType = "NTLM";
break;
}
client.EnableSsl = mailConfig.EnabledSsl;
client.Credentials = credential.GetCredential(mailConfig.MailServer, mailConfig.Port, authenticationType);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(mailMessage);
mailcode = MailState.Ok;
}
catch (SmtpException exception)
{
SmtpStatusCode statusCode = exception.StatusCode;
if (statusCode != SmtpStatusCode.GeneralFailure)
{
if (statusCode == SmtpStatusCode.MustIssueStartTlsFirst)
{
goto Label_01D3;
}
if (statusCode == SmtpStatusCode.MailboxNameNotAllowed)
{
goto Label_01CE;
}
goto Label_01D8;
}
if (exception.InnerException is IOException)
{
mailcode = MailState.AttachmentSizeLimit;
}
else if (exception.InnerException is WebException)
{
if (exception.InnerException.InnerException == null)
{
mailcode = MailState.SmtpServerNotFind;
}
else if (exception.InnerException.InnerException is SocketException)
{
mailcode = MailState.PortError;
}
}
else
{
mailcode = MailState.NonsupportSsl;
}
goto Label_01FA;
Label_01CE:
mailcode = MailState.UserNameOrPasswordError;
goto Label_01FA;
Label_01D3:
mailcode = MailState.MustIssueStartTlsFirst;
goto Label_01FA;
Label_01D8:
mailcode = MailState.SendFailure;
}
}
finally
{
}
}
Label_01FA:
mailInfo.Msg = GetMailStateInfo(mailcode);
return mailcode;
}
示例9: Submit
public HttpWebResponse Submit (Uri uri, FSpot.ProgressItem progress_item)
{
this.Progress = progress_item;
Request = (HttpWebRequest) WebRequest.Create (uri);
CookieCollection cookie_collection = Cookies.GetCookies (uri);
if (uri.UserInfo != null && uri.UserInfo != String.Empty) {
NetworkCredential cred = new NetworkCredential ();
cred.GetCredential (uri, "basic");
CredentialCache credcache = new CredentialCache();
credcache.Add(uri, "basic", cred);
Request.PreAuthenticate = true;
Request.Credentials = credcache;
}
Request.ServicePoint.Expect100Continue = expect_continue;
Request.CookieContainer = new CookieContainer ();
foreach (Cookie c in cookie_collection) {
if (SuppressCookiePath)
Request.CookieContainer.Add (new Cookie (c.Name, c.Value));
else
Request.CookieContainer.Add (c);
}
Request.Method = "POST";
Request.Headers["Accept-Charset"] = "utf-8;";
//Request.UserAgent = "F-Spot Gallery Remote Client";
Request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040626 Firefox/0.9.1";
Request.Proxy = WebProxy.GetDefaultProxy ();
if (multipart) {
GenerateBoundary ();
Request.ContentType = "multipart/form-data; boundary=" + boundary;
Request.Timeout = Request.Timeout * 3;
long length = 0;
for (int i = 0; i < Items.Count; i++) {
FormItem item = (FormItem)Items[i];
length += MultipartLength (item);
}
length += end_boundary.Length + 2;
//Request.Headers["My-Content-Length"] = length.ToString ();
if (Buffer == false) {
Request.ContentLength = length;
Request.AllowWriteStreamBuffering = false;
}
} else {
Request.ContentType = "application/x-www-form-urlencoded";
}
stream_writer = new StreamWriter (Request.GetRequestStream ());
first_item = true;
for (int i = 0; i < Items.Count; i++) {
FormItem item = (FormItem)Items[i];
Write (item);
}
if (multipart)
stream_writer.Write (end_boundary + "\r\n");
stream_writer.Flush ();
stream_writer.Close ();
HttpWebResponse response;
try {
response = (HttpWebResponse) Request.GetResponse ();
//Console.WriteLine ("found {0} cookies", response.Cookies.Count);
foreach (Cookie c in response.Cookies) {
Cookies.Add (c);
}
} catch (WebException e) {
if (e.Status == WebExceptionStatus.ProtocolError
&& ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.ExpectationFailed && expect_continue) {
e.Response.Close ();
expect_continue = false;
return Submit (uri, progress_item);
}
throw new WebException (Mono.Unix.Catalog.GetString ("Unhandled exception"), e);
}
return response;
}
示例10: SendMessage
/// <summary>
/// Sends the message.
/// </summary>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <param name="cc">The cc.</param>
/// <param name="bcc">The BCC.</param>
/// <param name="subject">The subject.</param>
/// <param name="HtmlMessage">The HTML message.</param>
/// <param name="textMessage">The text message.</param>
/// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
/// <param name="sendCallback">The send callback.</param>
/// <param name="asyncCallbackId">The async callback id.</param>
public static void SendMessage(
MailAddress from,MailAddressCollection to,
MailAddressCollection cc,MailAddressCollection bcc,
string subject,string HtmlMessage,string textMessage,
bool isHtml, SendCompletedEventHandler sendCallback, string asyncCallbackId)
{
MailMessage mailMsg = new MailMessage();
for(int x=0;to.Count>x;x++){
mailMsg.To.Add(to[x]);
}
if(cc!=null){
for(int x=0;cc.Count>x;x++) {
mailMsg.CC.Add(cc[x]);
}
}
if(bcc!=null) {
for(int x=0;bcc.Count>x;x++) {
mailMsg.Bcc.Add(bcc[x]);
}
}
mailMsg.Subject = subject;
mailMsg.IsBodyHtml = isHtml;
mailMsg.From = from;
mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
mailMsg.SubjectEncoding=System.Text.Encoding.ASCII;
if(isHtml){
mailMsg.Body = HtmlMessage;
}else{
mailMsg.Body = textMessage;
}
SmtpClient smtpClient = new SmtpClient();
if(Main.Site.smtp_authenticate){
NetworkCredential nc=new NetworkCredential();
nc.UserName=Main.Site.smtp_username;
nc.Password=Main.Site.smtp_password;
smtpClient.Credentials=(System.Net.ICredentialsByHost)nc.GetCredential(Main.Site.smtp_server,Convert.ToInt32(Main.Site.smtp_port),"Basic");
}
smtpClient.Host = Main.Site.smtp_server;
smtpClient.Port = Convert.ToInt32(Main.Site.smtp_port);
try{
smtpClient.Send(mailMsg);
}catch(Exception e){
String.Format("Error sending email: {0}",e.Message).Debug(8);
}
return;
}
示例11: PostAsync
public Task<HttpResponseMessage> PostAsync(Uri target, string postContent, string contentType)
{
const string UserAgent = "user-agent";
const string UserAgentValue = "EveHQ v{0}";
if (target != null)
{
var handler = new HttpClientHandler();
// This is never null
if (_proxyInfo != null && _proxyInfo.ProxyServerAddress != null)
{
// set proxy if required.
var proxy = new WebProxy(_proxyInfo.ProxyServerAddress);
if (_proxyInfo.UseDefaultCredential)
{
proxy.UseDefaultCredentials = true;
}
else
{
var credential = new NetworkCredential(_proxyInfo.ProxyUserName, _proxyInfo.ProxyPassword);
proxy.Credentials = _proxyInfo.UseBasicAuth ? credential.GetCredential(_proxyInfo.ProxyServerAddress, "Basic") : credential;
}
handler.Proxy = proxy;
handler.UseProxy = true;
}
handler.AutomaticDecompression = DecompressionMethods.GZip;
handler.AllowAutoRedirect = true;
var requestClient = new HttpClient(handler);
requestClient.DefaultRequestHeaders.Add(UserAgent, UserAgentValue.FormatInvariant(Version));
HttpContent content = !postContent.IsNullOrWhiteSpace() ? new StringContent(postContent, Encoding.UTF8, contentType) : null;
return requestClient.PostAsync(target, content);
}
return Task<HttpResponseMessage>.Factory.StartNew(() => null);
}
示例12: GetAsync
public Task<HttpResponseMessage> GetAsync(Uri target, string acceptContentType, HttpCompletionOption completionOption)
{
if (target != null)
{
var handler = new HttpClientHandler();
if (_proxyInfo != null && _proxyInfo.ProxyServerAddress != null)
{
// set proxy if required.
var proxy = new WebProxy(_proxyInfo.ProxyServerAddress);
if (_proxyInfo.UseDefaultCredential)
{
proxy.UseDefaultCredentials = true;
}
else
{
var credential = new NetworkCredential(_proxyInfo.ProxyUserName, _proxyInfo.ProxyPassword);
proxy.Credentials = _proxyInfo.UseBasicAuth ? credential.GetCredential(_proxyInfo.ProxyServerAddress, "Basic") : credential;
}
handler.Proxy = proxy;
handler.UseProxy = true;
}
handler.AutomaticDecompression = DecompressionMethods.GZip;
handler.AllowAutoRedirect = true;
var request = new HttpClient(handler);
if (!acceptContentType.IsNullOrWhiteSpace())
{
request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptContentType));
}
return request.GetAsync(target, completionOption);
}
return Task<HttpResponseMessage>.Factory.StartNew(() => null);
}