Published on: 19 January, 2016

Learn how to implement Web API service in DNN

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
09 September, 2016
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
09 September, 2016
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
12 September, 2016
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
06 February, 2017
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
03 January, 2017
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
15 May, 2017
Hi, How we can go further than [DnnAuthorize]. I mean, how I check module permissions in APIs?
andy
19 May, 2017
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.