[英]ASP.NET MVC 4 call a controller method from another controller
I am stuck on this issue. 我被困在这个问题上。 I have two controllers, UsersController and HomeController I am trying to call a controller method from UsersController from another controller (HomeController) by doing this: 我有两个控制器,UsersController和HomeController我正在尝试通过以下操作从另一个控制器(HomeController)的UsersController调用控制器方法:
UsersController usersController = new UsersController();
but I get this error: Generate constructor stub in 'CTHRC.Roti.Web.UI.Controllers.UsersController' 但我收到此错误:在“ CTHRC.Roti.Web.UI.Controllers.UsersController”中生成构造函数存根
I do not understand this error. 我不明白这个错误。
Here is my UsersController: 这是我的UsersController:
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using CTHRC.Roti.Domain.Api.Services;
using CTHRC.Roti.Domain.Model;
namespace CTHRC.Roti.Web.UI.Controllers
{
public class UsersController : ApiController
{
protected readonly UsersService UsersService;
public UsersController(UsersService usersService)
{
UsersService = usersService;
}
[HttpGet]
public dynamic Get(int UserId)
{
return UsersService.Get(UserId);
}
}
}
Here is my HomeController: 这是我的HomeController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
namespace CTHRC.Roti.Web.UI.Controllers
{
public class HomeController : Controller
{
//
// GET: /Default/
public ActionResult Index()
{
if (!WebSecurity.IsAuthenticated)
{
Response.Redirect("~/account/login");
}
UsersController userController = new UsersController();
return View();
}
}
}
What do I have to do to fix this? 我必须怎么做才能解决此问题? Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。 The reason I am trying to do this is because I want the data from the controller method. 我尝试执行此操作的原因是因为我想要控制器方法中的数据。
Your UsersController
does not have a parameterless constructor, which is expected by the call site. 您的UsersController
没有调用站点所期望的无参数构造函数。
You can add one like this: 您可以像这样添加一个:
public UsersController() {
}
Otherwise, you must provide a UsersService
as a parameter at the call site. 否则,您必须在调用站点上提供UsersService
作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.