Using the HttpWebRequest and HttpWebResponse Objects
<UserControl x:Class='SilverlightApplication3.MainPage'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DesignWidth='640'
d:DesignHeight='480'>
<Grid x:Name="LayoutRoot" Background="LightBlue">
<TextBlock Text="To:"/>
<TextBox x:Name="To" />
<TextBlock Text="From:"/>
<TextBox x:Name="From"/>
<TextBlock Text="Subject:"/>
<TextBox x:Name="Subject"/>
<TextBlock Text="Message:"/>
<TextBox x:Name="Body" AcceptsReturn="True" />
<Button x:Name="SendBtn" Content="Send"/>
<TextBlock x:Name="StatusText"/>
</Grid>
</UserControl>
//File:Page.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Net;
using System.IO;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
SendBtn.Click += new RoutedEventHandler(DoRequest);
}
void DoRequest(object sender, RoutedEventArgs e)
{
string serviceUrl = "http://myserver.com/mailservice.php";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(serviceUrl));
request.Method = "POST";
request.ContentType = "application/x-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(requestHandler),request);
}
void requestHandler(IAsyncResult asyncResult){
string postData = String.Format("ToAddr={0}&FromAddr={1}&Subject={2}&Body={3}",To.Text, From.Text, Subject.Text, Body.Text);
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
Stream requestStream = request.EndGetRequestStream(asyncResult);
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(postData);
writer.Flush();
writer.Close();
request.BeginGetResponse(new AsyncCallback(responseHandler),request);
}
void responseHandler(IAsyncResult asyncResult){
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
if (request.HaveResponse && response.StatusCode == HttpStatusCode.OK){
StreamReader reader = new StreamReader(response.GetResponseStream());
StatusText.Text = reader.ReadToEnd();
reader.Close();
}else{
StatusText.Text = "No Response From Mail Server";
}
LayoutRoot.Children.Remove(SendBtn);
}
}
}
Related examples in the same category