从HomeController调用Api服务

时间:2014-06-26 19:24:35

标签: c# asp.net .net asp.net-mvc-4

我正试图在我的Api服务中调用一个方法:

public IQueryable Get(int UserId){

     return UsersRepository.SelectAll().Where(ig => ig.Id == UserId);

}
来自我的HomeController的

UsersService.Get(UserId);

但我收到此错误:An object reference is required for the non-static field, method, or property 'CTHRC.Roti.Domain.Api.Services.UsersService.Get(int)'

我做错了什么?这是我的UserService:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CTHRC.Roti.Domain.Data.Repositories;
using CTHRC.Roti.Domain.Model;

namespace CTHRC.Roti.Domain.Api.Services
{
    public class UsersService
    {
        protected readonly IUsersRepository UsersRepository;

        public UsersService(IUsersRepository userRespository)
        {
            UsersRepository = userRespository;
        }

        public IQueryable Get(int UserId)
        {
            return UsersRepository.SelectAll().Where(ig => ig.Id == UserId);
        }
    }
}

这是我的家庭控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using CTHRC.Roti.Domain.Model;
using CTHRC.Roti.Domain.Api.Services;
using CTHRC.Roti.Domain.Data.Repositories;

namespace CTHRC.Roti.Web.UI.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            if (!WebSecurity.IsAuthenticated)
            {
                Response.Redirect("~/account/login");
            }
            int UserId = 1;
            UsersService.Get(UserId);
            return View();

        }

    }
}

这是我的IUsersRespository:

using System;
using System.Linq;
using CTHRC.Roti.Domain.Model;

namespace CTHRC.Roti.Domain.Data.Repositories
{
    public interface IUsersRepository : IRepository<Users>
    {

    }

}

1 个答案:

答案 0 :(得分:3)

您正在尝试像静态方法一样调用实例方法。 您必须实例化UsersService才能访问Get方法:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (!WebSecurity.IsAuthenticated)
        {
            Response.Redirect("~/account/login");
        }

        int UserId = 1;

        var service = new UsersService(userRepository);
        service.Get(UserId);

        return View();

    }
  }