我在我的应用程序中使用了MVC和WebApi。为了实现IoC,我使用结构图示例包(StructureMap.WebApi2)
在MVC控制器中一切正常但是当我使用web api时,例如将某些内容发布到服务器上我会收到此错误:
[HttpException]: The controller for path '/api/Activity/AddActivity' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
这是AddActivity行动:
[HttpPost]
[ActionName("AddActivity")]
public HttpResponseMessage AddActivity(ActivityDTO activityDTO)
{
ActivityDTO data = activityDTO;
HttpResponseMessage response = new HttpResponseMessage();
data.UserID = User.Identity.GetUserId();
int id = _activityServices.Add(data);
if (id != -1)
{
response = this.Request.CreateResponse(HttpStatusCode.OK, id);
}
else
{
response=this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Activity doesn't save.");
}
return response;
}
我检查了行动的路径,这是正确的。
你可以帮帮我吗?感谢
更新1:
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var container = IoCFactory.Container;
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator), new IoCWebApiControllerFactory(container));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ControllerActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ControllerApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
AjaxRequest:
$.post("/api/Activity/AddActivity", data)
答案 0 :(得分:1)
您的问题不是依赖项注入。在构造函数上放置一个断点,并检查注入的依赖项是否不为null。如果这些不为null,则说明您的设置正确。
您遇到路由问题。使用[ActionName("AddActivity")]
时,应该定义如下的路由:
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional } );
web-api的默认routeTemplate
没有{action}
部分。另外,您不应该在这里使用ActionName
,因为it has a different purpose。将其替换为Route
属性以使用attribute routing
功能。 More info