Saturday, November 19, 2016

Build an ASP.NET Core tag helper that consumes an Azure Web API RESTful service

Tag Helpers in ASP.NET Core allow you to create your own tags that fulfill a server-side purpose. In this tutorial, I will show you how to create a tag helper <cartoon-characters> that accesses a Web API service and displays contents in any razor view page.

The Web API service we will consume in this exercise is located at http://cartoonapi.azurewebsites.net/api/cartoon. It delivers the names of cartoon characters and their respective images.

1) To start with, create an ASP.NET Core Web application named TagHelperDemo in Visual Studio 2015.

2) We need to create a class that closely matches the nature of the Web API JSON object. Therefore, add the following CartoonCharacter class to a Models folder in your project:
public class CartoonCharacter {
  public string Name { get; set; }
  public string PictureUrl { get; set; }
}
3) Next, we will need to install the We API Client libraries. To that end, execute the following commands from within the Package Manager Console window in Visual Studio 2015:
Install-Package Microsoft.AspNet.WebApi.Client
Install-Package System.Runtime.Serialization.Xml
This should add the following dependencies to your project.json file:
"Microsoft.AspNet.WebApi.Client": "5.2.3",
"System.Runtime.Serialization.Xml":  "4.1.1"
4) Add the following tag to the bottom of Views/Home/About.cshtml:

<cartoon-characters></cartoon-characters>

5) Create a folder named TagHelpers and add to it a class file named CartoonCharactersTagHelper.cs. Have the class inherit from TagHelper and implement the ProcessAsync() method as follows:

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
}


We could have implemented a method Process() instead. However, in our case, it is appropriate to implement ProcessAsync() instead because we are about to make an async call to a remote service.

6) Add the following instance variable to the CartoonCharactersTagHelper class:
 private string baseUrl = "http://cartoonapi.azurewebsites.net";

7) Annotate the CartoonCharactersTagHelper class with the following:

[HtmlTargetElement("cartoon-characters")]
[HtmlTargetElement(Attributes = "cartoon-characters")]


The first annotation defines the tag <cartoon-characters> and the second defines the “cartoon-characters” attribute. This means that we have two different ways to produce the same output on a razor .cshtml view.

8) Add the following method to the CartoonCharactersTagHelper class:

async Task<IEnumerable<CartoonCharacter>> GetCartoonCharactersAsync() {
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(baseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    IEnumerable<CartoonCharacter> cartoonCharacters = null;
    try {
        // Get all cartoon characters
        HttpResponseMessage response = await client.GetAsync("/api/cartoon");
        if (response.IsSuccessStatusCode) {
            cartoonCharacters = response.Content.ReadAsAsync<IEnumerable<CartoonCharacter>>().Result;
        }
    } catch (Exception e) {
        System.Diagnostics.Debug.WriteLine(e.ToString());
    }

    return cartoonCharacters;
}


The above code makes a request to the Web API service and returns an IEnumerable<CartoonCharacter> collection with the results.

9) Add the following code inside the ProcessAsync() method:

IEnumerable<CartoonCharacter> cartoonCharacters = await GetCartoonCharactersAsync();
string html = string.Empty;
html += "<table><tr><th>Name</th><th>Picture</th></tr>";
foreach (var item in cartoonCharacters) {
    string photoUrl = baseUrl + "/" + item.PictureUrl;
    html += "<tr>";
    html += "<td>" + item.Name + "</td>";
    html += "<td><img src='" + photoUrl + "' style='width: 50px' /></td>";
    html += "</tr>";
}
html += "<tr><table>";
output.Content.SetHtmlContent(html);


The above code creates a table with the collection of cartoon characters so that it can be displayed wherever the tag helper is used.

11) Register the tag name in the Views/_ViewImports.cshtml file by adding the following to the list of tags that are already there:

@addTagHelper "TagHelperDemo.TagHelpers.CartoonCharactersTagHelper, TagHelperDemo"

You may need to adjust the above names depending on what you called your app and/or your tag helper class.

11) Compile and run your application then click on About. You should see the following output:

image

If you inspect the table in your browser, you will see the following:

image

The above is using the tag and not the attribute. Edit About.cshtml and comment out “<cartoon-characters></cartoon-characters>” and put the following <div> tag with the cartoon-characters attribute underneath it:
<div cartoon-characters></div>

Your About.cshtml should now look like this:
@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>
@*<cartoon-characters></cartoon-characters>*@
<div cartoon-characters></div>
When you run your application. you should see the same output as before. If you inspect the table you will see the following HTML source:

image

This proves to us that you can either use tags or attributes with TagHelpers in ASP.NET Core.




No comments:

Post a Comment