我有一个像这样的ModuleController。 (ASP Web API Controller )。 (工作正常)
using System.Collections.Generic;
using System.Web.Http;
using AMMS.Logger.Interfaces;
using AMMS.Service.Interfaces;
using AMMS.Service.Models;
namespace AMMS.Api.Controllers
{
public class ModuleController: ApiController
{
private readonly IModuleService _moduleService;
public ModuleController(IModuleService moduleService)
{
_moduleService = moduleService;
}
public List<AmmsModule> Get(string userId)
{
return _moduleService.GetModules(userId);
}
}
}
我想添加一个所有 Controller 都通用的功能。所以我添加了一个像这样的BaseController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using AMMS.Logger;
using AMMS.Logger.Interfaces;
namespace AMMS.Api.Controllers
{
public class BaseController : ApiController
{
private readonly ILoggerService _loggerService;
public BaseController(ILoggerService loggerService)
{
_loggerService = loggerService;
}
protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception)
{
_loggerService.LogInfo($"Exception : {exception}, MethodInfo : {methodInfo}, actionName: {actionName}");
return false;
}
}
}
然后更改我的 ModuleController 以继承此 BaseController
using System.Collections.Generic;
using System.Web.Http;
using AMMS.Logger.Interfaces;
using AMMS.Service.Interfaces;
using AMMS.Service.Models;
namespace AMMS.Api.Controllers
{
public class ModuleController: BaseController
{
private readonly IModuleService _moduleService;
private readonly ILoggerService _loggerService;
public ModuleController(IModuleService moduleService, ILoggerService loggerService) : base(loggerService)
{
_moduleService = moduleService;
_loggerService = loggerService;
}
public List<AmmsModule> Get(string userId)
{
return _moduleService.GetModules(userId);
}
}
}
但是添加 BaseController 后无法加载模块。 当我调试时,ModuleController的代码似乎没有执行。 ! 在客户端我得到--
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
这可能是什么原因(在添加 BaseController 之后,代码根本不执行)?
最佳答案
基础 Controller
将 private readonly ILoggerService _loggerService;
更改为 protected readonly ILoggerService _loggerService;
(如果您想在派生类中访问它)
模块 Controller :
using System.Collections.Generic;
using System.Web.Http;
using AMMS.Logger.Interfaces;
using AMMS.Service.Interfaces;
using AMMS.Service.Models;
namespace AMMS.Api.Controllers
{
public class ModuleController: BaseController
{
private readonly IModuleService _moduleService;
public ModuleController(IModuleService moduleService, ILoggerService loggerService) : base(loggerService)
{
_moduleService = moduleService;
}
public List<AmmsModule> Get(string userId)
{
return _moduleService.GetModules(userId);
}
}
}
关于c# - 在 asp.net mvc 中添加 BaseController 会出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738494/