【问题标题】:What is the best way to move your code out of the controller and into a helper method class in .NET Core将代码移出控制器并移入 .NET Core 中的辅助方法类的最佳方法是什么
【发布时间】:2022-01-20 22:47:21
【问题描述】:

如何将重复的代码部分从控制器中移出到 Helper Method 类,而不必在 .NET Core 中重复代码?如果我需要提供更多详细信息,请告诉我。

我需要将所有重复代码部分移出此控制器,以便我可以在需要它的所有其他控制器中调用此方法

用户控制器:

using myApp.Data;
using myApp.Models;
using myApp.Models.ViewModels;
using myApp.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
    
namespace myApp.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        private readonly ApplicationDbContext db;
        private readonly UserManager<ApplicationUser> userManager;
  
        public UserController(  ApplicationDbContext db,
                        UserManager<ApplicationUser> userManager)
        {
            this.db = db;
            this.userManager = userManager;
        }
    
        [HttpGet]
        public async Task<IActionResult> UpdateUserDetails(UpdateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByIdAsync(model.Id);

                if (user == null)
                {   
                    //Calling Repeated Code in this controller
                    return UserNotFound();
                }
                else
                {
                    user.FirstName = model.FirstName;
                    user.LastName = model.LastName;
                    user.UserName = model.UserName;
                    user.PhoneNumber = model.PhoneNumber;
                }

                var result = await userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    //Calling Repeated Code in this controller
                    return UpdateSuccess();
                }

                AddErrors(result);
            }

            return View(model);
        }
            
        //REPEATED CODE SECTION BEGINS (Extracted out of UpdateUserDetails Controller)
        public IActionResult UserNotFound()
        {
            TempData[HelperStatic.ErrorMessage] = HelperStatic.userNotFoundMsg;
            return View(HelperStatic.notFoundView);
        }
        
        public IActionResult UpdateSuccess()
        {
            TempData[HelperStatic.SuccessMessage] = HelperStatic.recordUpdatedMsg;
            return RedirectToAction(nameof(Index));
        }

        //REPEATED CODE SECTION ENDS
   }
}

项目中已经存在一个静态助手类,它只有静态常量。

上述控制器中使用的静态辅助类:

namespace myApp.Utilities
{
    public static class HelperStatic
    {
        // Messages
        public const string SuccessMessage = "Success";
        public const string ErrorMessage = "Error";
        public const string userNotFoundMsg = "User not found";
        public const string recordUpdatedMsg = "Record updated";

        // Views
        public const string notFoundView = "NotFound";
    }
}

我需要一个具有可重用操作方法的不同 HelperMethod 类。我如何做到这一点?

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-mvc .net-6.0


    【解决方案1】:

    创建一个控制器基类并将所有实用程序方法移入其中,而不是帮助类。

    public class BaseController : Controller
    {
        public IActionResult UserNotFound()
        {
            TempData[HelperStatic.ErrorMessage] = HelperStatic.userNotFoundMsg;
            return View(HelperStatic.notFoundView);
        }
    
        public IActionResult UpdateSuccess()
        {
            TempData[HelperStatic.SuccessMessage] = HelperStatic.recordUpdatedMsg;
            return RedirectToAction(nameof(Index));
        }
    }
    

    你可以这样使用它。

    public class HomeController : BaseController
    {
        public IActionResult Index()
        {
            UserNotFound();
            return View();
        }
    }
    

    【讨论】:

    • 如果我使用基本控制器,我可以在不同控制器之间共享基本控制器吗?
    • 是的。您需要从 BaseController 继承所有控制器。
    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多