ASP. NET 5 adventure (7): easy to implement single-page applications using hybrid controllers, asp.net Hybrid

Source: Internet
Author: User

ASP. NET 5 adventure (7): easy to implement single-page applications using hybrid controllers, asp.net Hybrid

(This article is also published in my public account "dotNET daily excellent article". Welcome to the QR code on the right to follow it .)

Note: in ASP. NET 5, the technology stacks of MVC and WEB APIs are merged, so it is also possible to develop a hybrid Controller.

As we all know, the technology stacks of ASP. net mvc 5 and web api 2 are independent (the development team is also independent ). Although the two can be integrated into the OWIN and run together later, the Controller code of the two cannot be written together (because the base classes of the two are inconsistent ). It is true that the MVC controller can return Json data to achieve the effect similar to that of the web api controller, but the design effect is not pure rest api.

Microsoft may also realize that providing two sets of technical stacks in parallel not only makes maintenance difficult for its own development, but also brings difficulties to users' learning and development. Therefore, in ASP. NET 5, the two are unified on the technology stack, that is, WEB APIs can be developed in MVC. The biggest embodiment of such technology integration is the routing ing mechanism. About ASP. I will not repeat the Routing Mechanism in NET 5. You can refer to other materials, such as "interpreting ASP. NET 5 & MVC6 series (11): Routing (http://www.cnblogs.com/TomXu/p/4496462.html ).

To make a SPA example, I tried to use a hybrid controller to support both view processing and REST data interface processing, the advantage of this is that you do not need to create two controllers for the MVC and REST APIs respectively, and can comply with the Action and routing style of the MVC and REST APIs at the same time. It may be difficult to describe the characteristics of the hybrid controller in words. Let's look at the Code directly.

Public class UserController: Controller {private AccountManager _ accountManager; public UserController (AccountManager accountManager) {_ accountManager = accountManager;} // The following is the mvc action // GET: /<controller>/public IActionResult Index () {return View ();} public IActionResult Edit (string id) {ViewBag. id = id; return View () ;}// The following is the api action [HttpGet ("[controller]/api")] public async Task <BasePagingListDto <UserDto> GetAll (int page = 1, int pageSize = 10) {var query = _ accountManager. userManager. users; var total = await query. countAsync (); var users = await query. skip (page-1) * pageSize ). take (pageSize ). toListAsync (); var dto = new BasePagingListDto <UserDto> (); dto. items = users. convertAll (user => Mapper. map <UserDto> (user); dto. total = total; return dto;} [HttpGet ("[controller]/api/{id}")] public async Task <IActionResult> GetById (string id) {var user = await _ accountManager. userManager. findByIdAsync (id); if (user = null) return HttpNotFound (); var dto = Mapper. map <UserDto> (user); return new ObjectResult (dto);} [HttpPut ("[controller]/api/{id}")] public async Task <IActionResult> EditById (string id, UserDto dto) {if (ModelState. isValid) {var user = await _ accountManager. userManager. findByIdAsync (id); if (user = null) return HttpNotFound (); dto. setValue (user); await _ accountManager. userManager. updateAsync (user); return new HttpStatusCodeResult (int) HttpStatusCode. accepted);} return new HttpStatusCodeResult (int) HttpStatusCode. badRequest );}}

In the code above, the Index Action returns a view (Index. cshtml) to the user. In this cshtml file, Layout. cshtml is used to obtain a unified master, which only contains a small number of Razor code. jQuery and Knockout are used to load and dynamically display data. The data is loaded through the Action GetAll, GET the address or use "@ Url. Action (" GetAll ")", and the actual access is GET "/User/api ".

Similarly, the Edit Action returns a view (Edit. cshtml) used to Edit user information. The GetById Action is used to load a single piece of User data, and the actual access is GET "/User/api/[userid]". When you need to modify data, use the EditById Action. The actual access address is PUT "/User/api/[userid]".

The Controller code can also be viewed through code snippets: http://git.oschina.net/ike/codes/8avtl3u2p6g1ik09c5snz

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.