尝试使用autofac使用属性路由的异常

时间:2017-01-03 09:42:29

标签: c# asp.net-web-api autofac asp.net-web-api-routing

当我尝试在我的操作上添加自定义路由属性时,我遇到了依赖注入问题。当我尝试使用Get,Post等标准方法时,一切正常。但是当我调用FindUsersByRole操作时,我收到错误:

  

System.InvalidOperationException:尝试创建类型为' UsersController'的控制器时发生错误。确保控制器具有无参数的公共构造函数。

堆栈追踪:

at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) 
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

内部异常:

  

System.ArgumentException:Type&#39; Novelis.WebApi.Controllers.UsersController&#39;没有默认构造函数

堆栈跟踪:

at System.Linq.Expressions.Expression.New(Type type) 
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) 
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) 
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

这是我的控制器的一部分:

[Authorize]
public class UsersController : ApiController
{
    private readonly IUsersRepository _usersRepository;

    public UsersController(IUsersRepository usersRepository)
    {
        _usersRepository = usersRepository;
    }

    //This is working fine
    [HttpGet]
    [ResponseType(typeof(List<UserInfoDto>))]
    public IHttpActionResult Get()
    {
        IList<UserInfoDto> values = _usersRepository.SelectAll();

        if (values == null || !values.Any())
            return Ok();

        return Json(new { collection = values });
    }

    //here I get an error
    [HttpGet]
    [Route("api/test/{roleId}/books")]
    public IHttpActionResult FindUsersByRole(int roleId)
    {
        // association code

        return Ok("test");
    }
}

以下是我打电话的网址:

localhost:81/api/Users - 工作正常

localhost:81/api/test/1/books - 错误

我还发布了我的配置类:

的Global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    AutofacConfig.Register();
}

AutofacConfig:

public class AutofacConfig
{
    public static void Register()
    {
        var builder = new ContainerBuilder();

        builder.RegisterModule(new AutoMapperModule());
        builder.RegisterApiControllers(typeof(WebApiApplication).Assembly).PropertiesAutowired();
        builder.RegisterModule(new NlogModule());
        builder.RegisterModule(new RepositoryModule());

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver =
             new AutofacWebApiDependencyResolver(container);
    }
}

WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Filters.Add(new ExceptionHandlingAttribute());
    }
}

启动:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        ConfigureOAuth(app);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
    }
}

1 个答案:

答案 0 :(得分:1)

您正在使用两个不同的HttpConfiguration。 IIS中GlobalConfiguration提供的那个以及您在Startup

中手动创建的那个

这是你的问题的原因。

删除HttpConfiguration中的所有Startup.cs代码,因为它导致与IIS和OWIN冲突。这通常是针对自托管的OWIN Web Api。

更新了启动

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);        
    }
}

其他一切都可以保持原样。