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

using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Net.Mail;
using System.Configuration;.

If namespace are missing in your project then add to use NuGet package manager. Write the code in your method.
   [HttpPost]
        public HttpResponseMessage SendMail(EmailConfigDetailsVM vm)
        {
    bool responce = false;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient smtpServer = new SmtpClient();
                string password = ConfigurationManager.AppSettings["password"];
                mail.From = new MailAddress(ConfigurationManager.AppSettings["MailFrom"]);
                string[] toRecipients = vm.ToRecipients.Split(',');
                foreach (string toRecipient in toRecipients)
                {
                    if (!string.IsNullOrEmpty(toRecipient))
                        mail.To.Add(new MailAddress(toRecipient));
                }
                
                mail.Subject = vm.Subject;
                mail.Body = vm.Body;
                vm.FromRecipients = ConfigurationManager.AppSettings["MailFrom"];
                smtpServer.Host = ConfigurationManager.AppSettings["Host"];
                smtpServer.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpServer.EnableSsl = bool.Parse(ConfigurationManager.AppSettings["EnableSsl"]);
                smtpServer.Timeout = 100000;
                smtpServer.Credentials = new System.Net.NetworkCredential(vm.FromRecipients, password);
                smtpServer.Send(mail);

var Result = this.Request.CreateResponse(HttpStatusCode.OK, responce, new JsonMediaTypeFormatter());
               
                return Result;
            }
            catch (Exception ex)
            {
                HttpError Error = new HttpError(ex.Message) { { "IsSuccess", false } };
                return this.Request.CreateErrorResponse(HttpStatusCode.OK, Error);
            }

	}
public class EmailConfigDetailsVM //Create New Class file for arguments
    {
        public string ToRecipients { get; set; }
        public string Body { get; set; }
        public string Subject { get; set; }
    }

Write Web.Config File

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

<appSettings>
    <add key="Port" value="587"/>
    <add key="Host" value="smtp.gmail.com" />
    <add key="MailFrom" value="XXXXX@gmail.com" />
    <add key="password" value="XXXX" />
    <add key="EnableSsl" value="True" />
  </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
<Grid>
        <Label Content="Email Id" HorizontalAlignment="Left" Margin="55,50,0,0" VerticalAlignment="Top"/>
        <Label Content="Email Body" HorizontalAlignment="Left" Margin="39,149,0,0" VerticalAlignment="Top"/>
        <Label Content="Email Subject" HorizontalAlignment="Left" Margin="26,100,0,0" VerticalAlignment="Top"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="133,54,0,0" TextWrapping="Wrap" Text="XXXX@gmail.com" VerticalAlignment="Top" Width="298" Name="txtid"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="133,100,0,0" TextWrapping="Wrap" Text="WPFTestMail" VerticalAlignment="Top" Width="298" x:Name="txtSubject"/>
        <RichTextBox HorizontalAlignment="Left" Height="81" Margin="133,149,0,0" VerticalAlignment="Top" Width="298" Name="txtBody">
            <FlowDocument>
                <Paragraph>
                    <Run Text="WPF"/>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>
        <Button Content="Send Mail" HorizontalAlignment="Left" Margin="133,253,0,0" VerticalAlignment="Top" Width="298" Height="37" Name="btnSendMail" Click="btnSendMail_Click"/>

    </Grid>

Using the namespace given above

using Newtonsoft.Json;
using System.Net.Http;
using System.Configuration;
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

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

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

<appSettings>
    <add key="MailApi" value="http://localhost:51537/api" />
 </appSettings>

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

private void btnSendMail_Click(object sender, RoutedEventArgs e)
        {
            EmailConfigDetailsVM emildetails = new EmailConfigDetailsVM();
            emildetails.ToRecipients = txtid.Text.ToString();
            emildetails.Body = new TextRange(txtBody.Document.ContentStart, txtBody.Document.ContentEnd).Text.ToString(); 
            emildetails.Subject = txtSubject.Text.ToString();
            var serializedProduct = JsonConvert.SerializeObject(emildetails);
            var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
            HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;
            if (response.IsSuccessStatusCode)
            {
                MessageBox.Show("Send Successfully");
            }
            else
            {
                MessageBox.Show("Send Failed...");
            }
        }

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..

emildetails.ToRecipients = txtmailId.Text.ToString();
            emildetails.Body = txtmailBody.Text.ToString();
            emildetails.Subject = txtmailSub.Text.ToString();
            var serializedProduct = JsonConvert.SerializeObject(emildetails);
            var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
            HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;
            if (response.IsSuccessStatusCode)
            {
               lblsuccess.Text="Send Successfully";
                lblerror.Text = "";
            }
            else
            {
                lblsuccess.Text = "";
                lblerror.Text="Send Failed...";
            }

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

MainPage = new App1.Page1();

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

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App1"
             x:Class="App1.MainPage">
<StackLayout x:Name="MasterLayout1" >
  <Label Text="Email Id" />
  <Entry x:Name="txtmailId" Text=" "></Entry>
  <StackLayout x:Name="MasterLayout2">

    <Label Text="Email Subject"
          
          HorizontalOptions="Center" />
    <Entry x:Name="txtmailSub" Text="XamarinTestMail"></Entry>
  </StackLayout>
  
  <StackLayout x:Name="MasterLayout3">
    <Label Text="Email Body"
          
            HorizontalOptions="Center" />
    <Entry x:Name="txtmailBody" Text="Hii"></Entry>  
  </StackLayout>
  
  <Button Clicked="MailSend_clicked" Text="Send Mail"></Button>
</StackLayout>
</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.

HttpClient client = new HttpClient();
        string apiUrl = "http://localhost:51537/api";     
emildetails.ToRecipients = txtmailId.Text.ToString();
            emildetails.Body = txtmailBody.Text.ToString();
            emildetails.Subject = txtmailSub.Text.ToString();
            var serializedProduct = JsonConvert.SerializeObject(emildetails);
            var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
            HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;
            if (response.IsSuccessStatusCode)
            {
                DisplayAlert("Alert", "Send Successfully", "OK");
            }
            else
            {
                DisplayAlert("Alert", "Send Failed...", "OK");
            }

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.

Happy Coding!