Learn Web API Using WPF, WebForms And Xamarin

What is ASP.NET Web API?

ASP.NET Web API is a framework to build Web API’s on the top of .NET framework, which makes it easy to build HTTP Services that comprises of range of clients, including mobile devices, all the Browsers & desktop Application.

Web API is a similar to ASP.NET MVC, so it contains all MVC features.

  • Model
  • Control
  • Routing
  • Model binding
  • Filter
  • Dependency injections

HTTP is not just for serving Web pages. It is also a powerful platform to build RESTful (Representational state transfer) API’s that expose Services and data. HTTP is simple, flexible & ubiquitous.

Why to use ASP.NET Web API?

Web API can be used anywhere in a wide range of client applications (Window & Web), Mobile device &  Browsers. Web API perfectly supports HTTP verbs (GET, POST, PUT, DELETE).

Xamarin

Create simple Web API to send a mail

Open Visual studio 2015. Go to New Project-> Select Visual C# -> Web & choose the project type as ASP.NET Web Application in the popup.

Xamarin

From the pop up given below, we will select the template as Web API.

Xamarin

Once the project is created, add new API in the controllers folder.->Right click on controllers-> add controller. Now, add Scaffold & Create as API Controller “SendMailApiController” will appear.

Xamarin

Using the namespace 

  1. using System.Net;  
  2. using System.Net.Http;  
  3. using System.Net.Http.Formatting;  
  4. using System.Web.Http;  
  5. using System.Net.Mail;  
  6. using System.Configuration;.  
  7.   
  8. If namespace are missing in your project then add to use NuGet package manager. Write the code in your method.  
  9.    [HttpPost]  
  10.         public HttpResponseMessage SendMail(EmailConfigDetailsVM vm)  
  11.         {  
  12.     bool responce = false;  
  13.             try  
  14.             {  
  15.                 MailMessage mail = new MailMessage();  
  16.                 SmtpClient smtpServer = new SmtpClient();  
  17.                 string password = ConfigurationManager.AppSettings["password"];  
  18.                 mail.From = new MailAddress(ConfigurationManager.AppSettings["MailFrom"]);  
  19.                 string[] toRecipients = vm.ToRecipients.Split(',');  
  20.                 foreach (string toRecipient in toRecipients)  
  21.                 {  
  22.                     if (!string.IsNullOrEmpty(toRecipient))  
  23.                         mail.To.Add(new MailAddress(toRecipient));  
  24.                 }  
  25.                   
  26.                 mail.Subject = vm.Subject;  
  27.                 mail.Body = vm.Body;  
  28.                 vm.FromRecipients = ConfigurationManager.AppSettings["MailFrom"];  
  29.                 smtpServer.Host = ConfigurationManager.AppSettings["Host"];  
  30.                 smtpServer.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);  
  31.                 smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;  
  32.                 smtpServer.EnableSsl = bool.Parse(ConfigurationManager.AppSettings["EnableSsl"]);  
  33.                 smtpServer.Timeout = 100000;  
  34.                 smtpServer.Credentials = new System.Net.NetworkCredential(vm.FromRecipients, password);  
  35.                 smtpServer.Send(mail);  
  36.   
  37. var Result = this.Request.CreateResponse(HttpStatusCode.OK, responce, new JsonMediaTypeFormatter());  
  38.                  
  39.                 return Result;  
  40.             }  
  41.             catch (Exception ex)  
  42.             {  
  43.                 HttpError Error = new HttpError(ex.Message) { { "IsSuccess"false } };  
  44.                 return this.Request.CreateErrorResponse(HttpStatusCode.OK, Error);  
  45.             }  
  46.   
  47.     }  
  48. public class EmailConfigDetailsVM //Create New Class file for arguments  
  49.     {  
  50.         public string ToRecipients { get; set; }  
  51.         public string Body { get; set; }  
  52.         public string Subject { get; set; }  
  53.     }   

Write Web.Config File

I am using Gmail domain & configuring from Mail ID in the Web.config file.

  1. <appSettings>  
  2.     <add key="Port" value="587"/>  
  3.     <add key="Host" value="smtp.gmail.com" />  
  4.     <add key="MailFrom" value="[email protected]" />  
  5.     <add key="password" value="XXXX" />  
  6.     <add key="EnableSsl" value="True" />  
  7.   </appSettings>  

Once you run the Application, Web API REST Services are ready to consume.

Xamarin

To call Web API method from

  • WPF (Native Application)
  • WebForm (Web Application)
  • Xamarin (Mobile Application)

    Xamarin

Consume Web API in WPF(Native Application)

To create WPF Application ->New Project ->select Windows & choose WPF Application.

Xamarin

Simply design the Windows, as shown below, using XAML code (e.x) getting parameters to Email id, Email subject & Email body.

Xamarin

XAML code 

  1. <Grid>  
  2.     <Label Content="Email Id" HorizontalAlignment="Left" Margin="55,50,0,0" VerticalAlignment="Top"/>  
  3.     <Label Content="Email Body" HorizontalAlignment="Left" Margin="39,149,0,0" VerticalAlignment="Top"/>  
  4.     <Label Content="Email Subject" HorizontalAlignment="Left" Margin="26,100,0,0" VerticalAlignment="Top"/>  
  5.     <TextBox HorizontalAlignment="Left" Height="23" Margin="133,54,0,0" TextWrapping="Wrap" Text="[email protected]" VerticalAlignment="Top" Width="298" Name="txtid"/>  
  6.     <TextBox HorizontalAlignment="Left" Height="23" Margin="133,100,0,0" TextWrapping="Wrap" Text="WPFTestMail" VerticalAlignment="Top" Width="298" x:Name="txtSubject"/>  
  7.     <RichTextBox HorizontalAlignment="Left" Height="81" Margin="133,149,0,0" VerticalAlignment="Top" Width="298" Name="txtBody">  
  8.         <FlowDocument>  
  9.             <Paragraph>  
  10.                 <Run Text="WPF"/>  
  11.             </Paragraph>  
  12.         </FlowDocument>  
  13.     </RichTextBox>  
  14.     <Button Content="Send Mail" HorizontalAlignment="Left" Margin="133,253,0,0" VerticalAlignment="Top" Width="298" Height="37" Name="btnSendMail" Click="btnSendMail_Click"/>  
  15.   
  16. </Grid>   

Using the namespace given above

  1. using Newtonsoft.Json;  
  2. using System.Net.Http;  
  3. using System.Configuration;  
  4. using System.Net.Http.Headers;  

Base code

After inserting the namespace, create new instance of the HttpClient, followed by setting its base URL to http://localhost:51537/api

  1. public MainWindow()  
  2.         {  
  3. HttpClient client = new HttpClient();  
  4.        string apiUrl = ConfigurationManager.AppSettings["MailApi"] + "/SendMailApi";   
  5.     client.BaseAddress = new Uri(apiUrl);  
  6.             client.DefaultRequestHeaders.Accept.Clear();  
  7.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  8. }  

This accepts header property instruction, which is sent to the Server in response of JSON format.

new MediaTypeWithQualityHeaderValue("application/json")

The URL will be set in App.config file

  1. <appSettings>  
  2.     <add key="MailApi" value="http://localhost:51537/api" />  
  3.  </appSettings>   

Follow the code given above, copy & paste the button click event.

  1. private void btnSendMail_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             EmailConfigDetailsVM emildetails = new EmailConfigDetailsVM();  
  4.             emildetails.ToRecipients = txtid.Text.ToString();  
  5.             emildetails.Body = new TextRange(txtBody.Document.ContentStart, txtBody.Document.ContentEnd).Text.ToString();   
  6.             emildetails.Subject = txtSubject.Text.ToString();  
  7.             var serializedProduct = JsonConvert.SerializeObject(emildetails);  
  8.             var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");  
  9.             HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;  
  10.             if (response.IsSuccessStatusCode)  
  11.             {  
  12.                 MessageBox.Show("Send Successfully");  
  13.             }  
  14.             else  
  15.             {  
  16.                 MessageBox.Show("Send Failed...");  
  17.             }  
  18.         }  

Enter any input in WPF Window & click Send Mail button.

Xamarin

Consume Web API in WebForms (Web Application)

To create Web application, go to New Project ->Visual C#->Select ASP.NET Web Application in this popup and choose the Web Forms templates.

Xamarin

Once the project is created, you can create new Web Forms and design the forms, as shown below.

Xamarin

Same WPF code style will follow to the Web Application. If there is no HttpClient, then get into NuGet Package Manager.

Xamarin

After installing the interface you can alter the WPF code for web Forms.. 

  1. emildetails.ToRecipients = txtmailId.Text.ToString();  
  2.        emildetails.Body = txtmailBody.Text.ToString();  
  3.        emildetails.Subject = txtmailSub.Text.ToString();  
  4.        var serializedProduct = JsonConvert.SerializeObject(emildetails);  
  5.        var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");  
  6.        HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;  
  7.        if (response.IsSuccessStatusCode)  
  8.        {  
  9.           lblsuccess.Text="Send Successfully";  
  10.            lblerror.Text = "";  
  11.        }  
  12.        else  
  13.        {  
  14.            lblsuccess.Text = "";  
  15.            lblerror.Text="Send Failed...";  
  16.        }   

Now, run the Web Application and the mail will be received from what mail id is configured in Web API.

Xamarin

Consume Web API in Xamarin (Mobile Application)

To create Mobile application, go to New Project ->Visual C#->select Cross-Platform & choose Blank App, using Portable class library in the popup.

Xamarin

Right click on App (Portable) & add new Item->Forms Xaml Page.

Xamarin

Navigate my page in App.xaml.cs file

  1. MainPage = new App1.Page1();  

Just write XML code for an Android mobile UI, as shown below. 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:App1"  
  5.              x:Class="App1.MainPage">  
  6. <StackLayout x:Name="MasterLayout1" >  
  7.   <Label Text="Email Id" />  
  8.   <Entry x:Name="txtmailId" Text=" "></Entry>  
  9.   <StackLayout x:Name="MasterLayout2">  
  10.   
  11.     <Label Text="Email Subject"  
  12.             
  13.           HorizontalOptions="Center" />  
  14.     <Entry x:Name="txtmailSub" Text="XamarinTestMail"></Entry>  
  15.   </StackLayout>  
  16.     
  17.   <StackLayout x:Name="MasterLayout3">  
  18.     <Label Text="Email Body"  
  19.             
  20.             HorizontalOptions="Center" />  
  21.     <Entry x:Name="txtmailBody" Text="Hii"></Entry>    
  22.   </StackLayout>  
  23.     
  24.   <Button Clicked="MailSend_clicked" Text="Send Mail"></Button>  
  25. </StackLayout>  
  26. </ContentPage>   

Run the mobile Application. This page appears in mobile device or an app will open an Android Emulator Manager.

Xamarin

Follow the same HttpClient settings & alter the code based on mobile UI in the button clicked event. 

  1. HttpClient client = new HttpClient();  
  2.         string apiUrl = "http://localhost:51537/api";       
  3. emildetails.ToRecipients = txtmailId.Text.ToString();  
  4.             emildetails.Body = txtmailBody.Text.ToString();  
  5.             emildetails.Subject = txtmailSub.Text.ToString();  
  6.             var serializedProduct = JsonConvert.SerializeObject(emildetails);  
  7.             var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");  
  8.             HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;  
  9.             if (response.IsSuccessStatusCode)  
  10.             {  
  11.                 DisplayAlert("Alert""Send Successfully""OK");  
  12.             }  
  13.             else  
  14.             {  
  15.                 DisplayAlert("Alert""Send Failed...""OK");  
  16.             }   

After click button, the mail is sent specified to the Email id.

Xamarin

Finally, we have used ASP.NET Web API in different types of Application.

Xamarin

Conclusion

In this article, we have learned Web API, using WPF, WebForms and Xamarin. If you have any queries, please tell me through the comments section.


Similar Articles