问题:
我正在使用MVC4 WebAPI,并且在Get()调用期间抛出错误。

错误:



堆栈跟踪:

at System.Linq.Expressions.Expression.New(Type type)
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}

我很乐意提供所需的任何代码,只要让我知道您想看到的内容即可。

Controller :
namespace Comments2.Controllers
{
    //[Authorize]
    public class CommentsController : ApiController
    {
        ICommentRepository repository;

    public CommentsController(ICommentRepository repository)
    {
        this.repository = repository;
    }

    [Queryable]
    public IQueryable<Comment> GetComments()
    {
        return repository.Get().AsQueryable();
    }

    public Comment GetComment(int id)
    {
        Comment comment;
        if (!repository.TryGet(id, out comment))
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        return comment;
    }
}

JavaScript:
$(function() {
    $("#getComments").click(function () {
        // We're using a Knockout model. This clears out the existing comments.
        viewModel.comments([]);

        $.get('/api/comments', function (data) {
            // Update the Knockout model (and thus the UI) with the comments received back
            // from the Web API call.
            viewModel.comments(data);
        });

    });
});

最佳答案

好像您使用的是HttpControllerActivator的默认实现,该实现不适用于依赖项注入(inject)。尝试this,它集成了unity容器来处理依赖关系,但是您可以对其进行修改以使用所需的DI的任何实现。

关于c# - 错误 “CommentsController does not have a default constructor”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11495776/

10-12 12:34
查看更多