Configuring Silverlight RIA Services App to Use ASP.Net Web APIs

If you are developing a Silverlight RIA Service Application & you need to expose your GET or POST methods via the API calls that could be consumed by third-party apps then you can very easily utilize the ASP.Net Web API for that.

In today's article we will see how to configure an existing Silverlight RIA Services Enabled app to use Web APIs.

To summarize, the following steps are needed to create a RIA Enabled Silverlight App hosted in an ASP.Net Web App.

  1. Create a new project, select "Enable RIA services" & choose to host it within an ASP.Net Web App.
  2. Add a new ADO.Net Entity Data Model Class (if you are using RIA services then you would most likely already have your Database in place) based on one of the tables available in your database. In my example the table is called Groups.
  3. Build the project & add a Domain Service based, enable editing & generation of its metadata.

    With this you will have a project structure like this:

    Silverlight-RIA-Services-1.jpg
     
    With this in place, let's get started with configuring it for Web API.

    First, we need the important bits that the Web API needs. Nuget is handy for this task.
     
  4. Fire it up on your .Web Project (SlRiaWebApiDemo.Web in this case) & search for a package called "Microsoft.AspNet.WebApi.SelfHost" & install it after accepting the license terms.

    This will install everything we will need to work with the Web API.

    Once you have the bits installed & ready, it's time to add the API Controller.
     
  5. Right-click on your .Web project then select "Add New Item" then select "Web API Controller Class" and name it "GroupsController".

    Please ensure that the name is correct because this is what will resolve the controller at a later stage & will call the methods within it.

    Silverlight-RIA-Services-2.jpg
     
  6. Notice this class is not derived from Controller but from ApiController.
  7. Using my entities I created a new context that I can use to query my database. Here is my controller class.
     

    using System.Collections.Generic;

    using System.Linq;

    using System.Web.Http;

     

    namespace SLRiaWebAPiDemo.Web

    {

       public classGroupsController : ApiController

        {

            MRM_LatestEntities _context = new MRM_LatestEntities();

     

            //List<Group> groups = new List<Group>();

     

     

            // GET api/<controller>

           public IEnumerable<Group> GetAllGroups()

            {

               return _context.Groups;

     

                //return new string[] { "value1", "value2" };

            }

     

            // GET api/<controller>/5

           public Group GetGroupById(int id)

            {

               return _context.Groups.Where(x => x.Id == id).FirstOrDefault();

                //return "value";

            }

     

            // POST api/<controller>

           public void Post([FromBody]string value)

            {

            }

     

            // PUT api/<controller>/5

           public void Put(int id, [FromBody]string value)

            {

            }

     

            // DELETE api/<controller>/5

           public void Delete(int id)

            {

            }

        }

    }

      
     Finally we need to tell our app to route to this controller when the URL is looking for it. In order to do this we need to add the controller mappings in the configurations of our app.
     

  8. Add a new class file & name it "WebApiConfig.cs". This class will have the configuration code we need.
     

    using System.Web.Http;

     

    namespace SLRiaWebAPiDemo.Web

    {

       public classWebApiConfig

        {

           public staticvoid Register(HttpConfiguration config)

            {

                config.Routes.MapHttpRoute(

                    name:"DefaultApi",

                    routeTemplate: "api/{controller}/{id}",

                    defaults:new { id = RouteParameter.Optional }

                    //defaults: new { controller = "Test", action = "Get", id = "" }

                );

            }

        }

    } 
     

  9. Finally we need to register these configuration details in the Web API Configuration. To do this again add a new item to the .Web project & choose "Global Application Class". This will add a Global.asax file to the project that has app level events like App_Start, Session_Start and so on.
     
  10. Open this file & write the following within App_Start:
     

    using System;

    using System.Web.Http;

     

    namespace SLRiaWebAPiDemo.Web

    {

       public classGlobal : System.Web.HttpApplication

        {

           protected void Application_Start(object sender,EventArgs e)

            {

                WebApiConfig.Register(GlobalConfiguration.Configuration);

            }

        }

    }

        
    That's all we need. Put a breakpoint at the GetAllGroups() method in WebApi Controller & hit F5.

    When the app is up & running for example http://localhost:1778/Default.aspx change it to http://localhost:1778/api/groups/   Hit enter and you will see that the breakpoint is hit. Continue debugging & you will see the JSON data in the browser.

Conclusion

This was a very basic example that shows how you can configure your Silverlight RIA Service or ASP.Net app to use the Web API without actually getting started with a full blown MVC project.

You can create multiple APIs & release them to be used by your clients.


Similar Articles