Published on: 19 January, 2016

Learn how to implement Web API service in DNN

Posted by andy | 5113 views 1 likes 2 favourites 6 comments
Tumblr Digg Google Plus

It is a really good news for the DNN lover, on version 7.0 has now supported the powerful and light weight Web API. Although the DNN still use the web forms technology which has been outweighed by ASP.Net MVC, I am still thinking it is still a great technology as until the latest version, it is still supported by Microsoft.

In order to enable the Web API, you will need to add the following dll reference into your project. The first two dll can referenced from the bin folder of your DotNetNuke folder. The files you need to reference are:

  • DotNetNuke.dll
  • DotNetNuke.Web.dll
  • System.Net.Http.dll
  • System.Net.Http.Formatting.dll
  • System.Web.Http.dll

Once you have done this, you will need to register your controller class. Please make sure that you reference DotNetNuke.Web.Api and inherits the IServiceRouteMapper.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Web.Api;

namespace MyModuleName.WebAPI {
    public class RouterMapper : IServiceRouteMapper {
        public void RegisterRoutes(IMapRoute mapRouteManager) {
            mapRouteManager.MapHttpRoute("MyModuleName.WebAPI", "default", "{controller}/{action}", new[] { "MyModuleName.WebAPI" });
        }
    }
}

Once the routing mapper for your controller has already been created. We can start creating your first Web API service. You will learn how to create Web Service API that will accept a post and get object. In addition, you will learn how to give access to Web API for logged in users only.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Http;
using DotNetNuke.Web.Api;
using System.Net.Http;
using System.Net;
using System.Text;

namespace MyModuleName.WebAPI {
    public class HelloWorldController : DnnApiController {
        [HttpPost]
        public HttpResponseMessage PostMyName([FromBody] yourName) {
            try {
                return Request.CreateResponse(HttpStatusCode.OK, "Hello World " + yourName);
            } catch (Exception ex) {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
		
	[HttpGet]
        public HttpResponseMessage GetMyName([FromBody] yourName) {
            try {
                return Request.CreateResponse(HttpStatusCode.OK, "Hello World " + yourName);
            } catch (Exception ex) {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
		
	[HttpPost]
	[DnnAuthorize]
        public HttpResponseMessage PostMyName([FromBody] PersonInfo objPerson) {
            try {
                return Request.CreateResponse(HttpStatusCode.OK, "Hello World " + objPerson.FirstName + " " + objPerson.LastName);
            } catch (Exception ex) {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
    }
}

If you see above example, you can see to determine if a Web API service only apply for post or get only is by identifying the header [HttpPost] and [HttpGet]. While to make the service only can be accessed by logged user is by specifying [DnnAuthorize] on above of your method code.

Once you do the Web Service API class you can try the DNN Web Service by using JQuery script to perform post and get action. See below example for more details. What you need to remember on the Web API URL in DNN is you need to follow this format:

/desktopmodules/namespace-of-your-module/API/controller-name/method-name
//Example of using POST
var jsonData = {
	FirstName: 'Brian',
	LastName: 'James'
}
$.ajax({
	url: "/desktopmodules/MyModuleName.WebAPI/API/HelloWorld/PostMyName",
	cache: false,
	type: 'POST',
	contentType: 'application/json; charset=utf-8',
	data: JSON.stringify(jsonData),
	success: function (response) {
		console.log(response);
	},
	error: function (xhr, ajaxOptions, thrownError) {
		console.log(xhr.responseText);
	}
})

//Example of using GET
var myName = 'James';
$.ajax({
	type: "GET",
	url: "/desktopmodules/MyModuleName.WebAPI/API/HelloWorld/GetMyName?yourName" + myName,
	contentType: "application/json; charset=utf-8",
	dataType: "json",
	success: function (response) {
		console.log(response);
	},
	error: function (xhr, ajaxOptions, thrownError) {
		console.log(xhr.responseText);
	}
});
Comments
Patrik Johansson
Commented on: 09 Sep, 2016 12:13:21 AM
Hi, Good attempt but there are so much important stuff missing here that I wonder if it will actually help people trying to do this or not. Like no mentioning that you have to change the output of the build and that the class PersonInfo is referenced in the code above but not declared etc. /Patrik Johansson
andy
Commented on: 09 Sep, 2016 09:14:04 AM
Thanks Patrik for pointing that out. You are actually right. The class codes need to be placed into separated project so it can be built as an independence dll object which can be referenced into the site. Alternatively you can place the class under the App_Code folder. But recommend for all to make it as a separate project would be better.
Patrik J
Commented on: 12 Sep, 2016 06:08:27 PM
Hi, Yes, the WebAPI in DNN was a bit tricky to get going as the documentation is quite lacking and there are a few pitfalls to consider. Also DNN themselves have several outdated articles about this. So kudos for giving a good explanation above, just need some additional info to get everyone going :)
andy
Commented on: 06 Feb, 2017 09:38:10 PM
Hi Saed, Please see below answers. 1. Unfortunately you can't, unless you modify the core dnn source code. 2. It should be in json format when you send and receive from server? Unless I didnt get it right? 3. There are some paid module that cover alternative login details but unfortunately, it still need to be bind into DNN users table. Unless you can create login details and by pass dnn users. Again this will be a lot of troubles as it links to module and page permission etc. Not recommend to do this.
Saeed Nemati
Commented on: 03 Jan, 2017 06:39:57 PM
Hi, thanks for this good article. I have many questions: 1) Can we somehow reduce that long ugly path? We need to do this because it helps our productivity and quality in mass encounters with services. 2) How can we configure DNN to remove XML formatter from all request/responses? We only work with JSON and sometimes with form-url-encoded. That's it. How can we manage formatters in general? 3) Is it possible for us to have our own user management based on DNN users? In other words, whatever DNN has, let it manage users and roles and permissions. Whatever we have, let us manage users and roles and permissions. Like for example in API instead of using DnnAuthorize, I want to use my own user management infrastrcuture. Somehow I can think of SSO or Open ID & Open ID Connect. Thank you so much.
Ehsan
Commented on: 15 May, 2017 09:54:07 PM
Hi, How we can go further than [DnnAuthorize]. I mean, how I check module permissions in APIs?
andy
Commented on: 19 May, 2017 08:59:29 AM
Hi Ehsan, I do not find any documentation on how to include the role in the documentation. Best way probably to pass the user id and page id or module id and check against the role of user against the module or page permission. If you need to check against specific roles that can access the web api, you can use this: [DnnAuthorize(StaticRoles = "MyRoleNameHere")]
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Related Articles
Published on: 22 May, 2016
If you want to use Gmail SMTP in your DNN website, this can be easily done by specifying the correct port 587 in the SMTP settings. Unfortunately, there is no port number field supplied in the SMTP settings form. So in order to include the port number, you just need to add the smtp.gmail.com:587 in the SMTP settings.
Published on: 21 May, 2016
There are two options to setup the skin template into the DNN website, the first option is to globally set all pages using the default skin template and the second option is to set the skin template manually to each page. Usually when you create skin templates in DNN, there are at least 2 skins will be created. One would be the home page skin and the rest is the generic page skin.
Published on: 12 March, 2015
Have you encountered a problem where you completely forgot your super account login details of your DNN site? Well if you do and you still have the access to the ftp of the site, the following simple code trick should be able to help you solve this problem.
Published on: 20 October, 2013
DNN CMS has included an overlay transparency when you are in edit mode. This sometimes quite annoying especially when you have a white background and this layer has caused a blur effect overlaying the content of your site.
Related Tutorials
Published on: 17 February, 2017
In this tutorial you will learn how to install a DNN theme package. Before you can install the DNN skin package. You will need to log in as a super account user. The way to install the skin is exactly the same to install a module extension.
Published on: 14 May, 2016
Learn how to create your first new skin template in DNN. You will also learn what are required to create the DNN skin template and what is the structure of the template looks like.
Published on: 14 April, 2016
DNN has a built in Localization framework to help you create website with multiple languages support. By default, the common HTML module shipped in DNN installation does support this feature. Unfortunately, not all of the third party modules available would be able to support multiple languages. If they do, usually they only support the languages via resx files.
Published on: 05 February, 2016
In this tutorial you will learn how to create your first DNN module. This will be a basic module that will display Hello World. You will learn also how to get a module setting and save the value into module settings table and display it on the screen.
Published on: 18 December, 2015
Learn how to manage users in DNN. Features including change password, delete user account, edit existing user account or manage user role access. To access this feature, you need to have an administrator access.