我有一個像這樣的ModuleController。 (ASP Web API控制器)。 (它的正常工作)在asp.net mvc中添加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: ApiController
{
private readonly IModuleService _moduleService;
public ModuleController(IModuleService moduleService)
{
_moduleService = moduleService;
}
public List<AmmsModule> Get(string userId)
{
return _moduleService.GetModules(userId);
}
}
}
我想添加一個函數,它是通用於所有Controllers.So我加入這樣的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的代碼似乎並沒有執行。 ! 在客戶端,我得到 -
無法加載資源:服務器的狀態爲迴應500 (內部服務器錯誤)
什麼可以這樣做的原因(剛添加一個BaseController後,代碼根本不會執行)?
可能是因爲您在此BaseController和ModuleController中都聲明瞭the_loggerService屬性?嘗試將BaseController中的the_loggerService的可見性更改爲內部並從ModuleController中除去_loggerService屬性 – bolt19
您應該不必在派生類中觸及_loggerService,而是調用基類構造函數。 –
謝謝,它工作! @JohnM –