Điều kiện cần là trong thư mục bin của framework có các dll sau đây
- DotNetNuke.dll
- DotNetNuke.Web.dll
- System.Net.Http.dll
- System.Net.Http.Formatting.dll
- System.Web.Http.dll
Tiếp theo là tạo một class RouterMapper để làm nhiệm vụ router cho api trỏ vào đúng hàm mình viết trong module
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" });
}
}
}
ở trên bạn đã khai báo folder hệ thống chứa code, sau đó là tên controller (class xử lý) và action là tên phương thức (method xử lý), cái cuối cùng sau new[] các bạn để tên namespace của module đó nha
sau khi tạo router xong thì api sẽ ở địa chỉ này
/desktopmodules/MyModuleName.WebAPI/api/{controller}/{action}
Bây giờ thì tạo controller với action thôi
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);
}
}
} }
Ở trên ta vừa tạo Controller có tên là HelloWorld (HelloWorldController) kế thừa từ DnnApiController
Reponse thì ta có thể tự thiết kế để trả về object kiểu gì mà ta muốn
Đơn giản vậy thôi nha, vừa rồi mình đã chỉ cho các bạn thiết kế web api
/desktopmodules/MyModuleName.WebAPI/api/HelloWorld/GetMyName
trong DotnetNuke nha, chúc các bạn một ngày nghiên cứu công nghệ vui vẻ

No comments:
Post a Comment