You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC调用REST Web API提示控制器无默认构造函数错误如何解决?

问题原因

ASP.NET Web API 默认的控制器激活逻辑要求控制器必须提供公共无参数构造函数,你当前的WebApiController只定义了一个带GetToken_BLL类型参数的构造函数,且没有配置依赖注入(DI)容器来负责构造函数的参数注入,因此框架无法完成控制器实例化,抛出该错误。
另外你当前代码中注入的_tokenService字段完全没有被使用,Token方法内仍然手动实例化了GetToken_BLL对象,注入逻辑属于冗余代码。

解决方案

方案1:快速修复(适用于不需要依赖注入的场景)

直接给控制器添加公共无参数构造函数即可,代码如下:

public class WebApiController : ApiController
{
    private readonly GetToken_BLL _tokenService;
    // 新增无参数构造函数
    public WebApiController()
    {
    }
    // 原有带参构造函数可以保留也可以删除
    public WebApiController(GetToken_BLL tokenService)
    {
        _tokenService = tokenService;
    }
    // 剩余原有代码不变
}

方案2:规范依赖注入实现(推荐)

如果你需要使用依赖注入降低耦合,按以下步骤修改:

  1. 首先修改Token方法,删除手动实例化GetToken_BLL的代码,改用注入的_tokenService:
[HttpPost]
[Route("api/Token")]
public IHttpActionResult Token()
{
    stcAPIMessage message = new stcAPIMessage();
    // 删除这行代码:GetToken_BLL tokenbll = new GetToken_BLL();
    var result = _tokenService.GetToken();
    // 剩余逻辑不变
}
  1. 配置依赖注入容器:
  • 如果是ASP.NET Core Web API:在Program.cs(或Startup.cs的ConfigureServices方法)中注册GetToken_BLL即可,框架自带的DI容器会自动处理控制器注入:
builder.Services.AddScoped<GetToken_BLL>();
  • 如果是**.NET Framework 版本的ASP.NET Web API**:需要引入Unity、Autofac等第三方DI容器,以Unity为例:
    1. 安装NuGet包Unity.AspNet.WebApi
    2. 在Global.asax.cs的Application_Start方法中添加配置:
    var container = new UnityContainer();
    container.RegisterType<GetToken_BLL>();
    GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    

额外优化建议

你当前调用PostAsync、ReadAsStringAsync时都使用了.Result同步阻塞调用,在Web场景下很容易引发线程死锁,建议改为异步方法+await的方式调用。


内容的提问来源于stack exchange,提问作者fahime abouhamze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:27:03