使用自定义路由令牌和属性路由时如何避免重复?

问题描述 投票:0回答:1

现在,我在asp.net核心mvc应用程序中具有以下代码:

using System.Threading.Tasks;
using jean.nl.Extensions;
using jean.services.Constants;
using jean.services.Extensions;
using jean.services.Repositories;
using jean.services.Services;
using Microsoft.AspNetCore.Mvc;

namespace jean.nl.Areas.Employer.Controllers
{
    [Area(AreaConstants.Employer)]
    [Route("[area]/Employee/Notify")]
    public class EmployeeNotificationController : BaseController
    {
        private readonly UserRepository _userRepository;
        private readonly EmployeeRegistrationService _employeeRegistrationService;
        public EmployeeNotificationController(UserRepository userRepository,
            EmployeeRegistrationService employeeRegistrationService)
        {
            _userRepository = userRepository;
            _employeeRegistrationService = employeeRegistrationService;
        }

        [Route("{employeeId}/[action]")]
        public async Task<bool> RegistrationPending(string employeeId)
        {
            return await _employeeRegistrationService
                .NotifyRegistrationPendingAsync(User.UserId(), employeeId);
        }

        [Route("{employeeId}/[action]")]
        public async Task<bool> IdUploadPending(string employeeId)
        {
            return await _employeeRegistrationService
                .NotifyIdUploadPendingAsync(User.UserId(), employeeId);
        }

        [Route("{employeeId}/[action]")]
        public async Task<bool> ContractSignaturePending(string employeeId)
        {
            return await _employeeRegistrationService
                .NotifyContractSignaturePendingAsync(User.UserId(), employeeId);
        }

        [Route("{employeeId}/[action]")]
        public async Task<bool> DocumentSignaturePending(string employeeId)
        {
            return await _employeeRegistrationService
                .NotifyDocumentSignaturePendingAsync(User.UserId(), employeeId);
        }
    }
}

我正在实现的目标是匹配~/Employer/Employee/Notify/{employeeId}/{action}类型的网址。虽然这种方法成功了,但我不禁感到有很多不必要的重复。一方面,每个动作都标记有相同的Route属性,这使我怀疑我是否可以不同地实现同一目标。我尝试使用以下代码段定义表单的全局路由,

routes.MapRoute(
    name: "notify_employee",
    template: "{area:exists}/Employee/Notify/{employeeId}/{action}",
    defaults: new { controller = "EmployeeNotificationController" });

但无济于事。有什么方法可以使我寻找所需的东西,从而避免我不得不修饰控制器的每个动作?

c# asp.net-core asp.net-core-mvc asp.net-core-2.2
1个回答
0
投票

经过一番思考,我通过以下方式定义route属性和action方法找到了解决方案:

[Route("[area]/Employee/{id:guid}/Notify/[action]")]
public class EmployeeNotificationController : BaseController
{
    // some code...

    public async Task<bool> RegistrationPending(string id)
    {
        return await _employeeRegistrationService
            .NotifyRegistrationPendingAsync(User.UserId(), id);
    }

    // some more code...
}
© www.soinside.com 2019 - 2024. All rights reserved.