Learn Web API Using WPF, WebForms, and Xamarin
Do you love ASP.NET Core? Then read on to learn how to use its Web API to create applications for both native and web applications.
Join the DZone community and get the full member experience.
Join For Freewhat is the asp.net web api?
asp.net web api is a framework to build web apis on top of the .net framework, which makes it easy to build http services that comprise of a range of clients, including mobile devices, web browsers, and desktop applications.
web api is similar to asp.net mvc, so it contains all of mvc's 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) apis that expose services and data. http is simple, flexible, and ubiquitous.
why use the asp.net web api?
web api can be used anywhere in a wide range of client applications (windows and web), mobile devices, and browsers. web api perfectly supports http verbs (get, post, put, delete).
create a simple web api to send an email
open visual studio 2015. go to new project-> select visual c# -> web and choose the project type, asp.net web application, in the pop-up.
from the pop-up, given below, we will select the web api template.
once the project is created, add a new api in the controllers folder. ->right click on controllers-> add controller. now, add scaffold and create as api controller. if you've done it properlyl, “sendmailapicontroller” will appear.
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; }
}
if namespace is missing in your project, then add the nuget package manager. write the code in your method.
write web.config file
i am using the gmail domain and configuring from the 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.
calling the web api method
in this section, we'll call the web api method from the following:
- wpf (native application)
- webform (web application)
-
xamarin (mobile application)
consume web api in wpf (native application)
to create a wpf application, go to new project, select windows and choose wpf application.
simply design the windows, as shown below, using xaml code, and give parameters to email id, email subject, and email body.
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 a 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, as a response, in json format.
new mediatypewithqualityheadervalue("application/json")
the url will be set in the app.config file:
<appsettings>
<add key="mailapi" value="http://localhost:51537/api" />
</appsettings>
follow the code given above, and copy and 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 the wpf window and click the send mail button.
consume web api in webforms (web application)
to create a web application, go to new project ->visual c#->select asp.net web application. in this pop-up, choose the web forms template.
once the project is created, you can create new web forms and design the forms, as shown below.
the same wpf code style will be used by the web application. if there is no httpclient, then get it from the nuget package manager.
after installing the interface you can alter the wpf code for web forms, like so:
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 email will be received from the email id that is configured in web api.
consume web api in xamarin (mobile application)
to create a mobile application, go to new project ->visual c#->cross-platform, and choose blank app, using the portable class library in the pop-up.
right click on app (portable) and add new item->forms xaml page.
navigate to the main page in the 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 on the mobile device or an app will open an android emulator manager.
follow the same httpclient settings and 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 clicking the button, the mail is sent to the specified email id.
conclusion
in this article, we have learned how to use web api, by sing wpf, webforms, and xamarin. if you have any queries, please tell me through the comments section .
Published at DZone with permission of Thiruppathi Rengasamy, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments