Call Api Service from HomeController

本文关键字:HomeController from Service Api Call | 更新日期: 2023-09-27 18:10:38

我正在尝试调用我的Api服务中的方法:

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

from my 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);
        }
    }
}

这是我的Home Controller:

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();
        }
    }
}

这是我的iusersrepository:

using System;
using System.Linq;
using CTHRC.Roti.Domain.Model;
namespace CTHRC.Roti.Domain.Data.Repositories
{
    public interface IUsersRepository : IRepository<Users>
    {
    }
}

Call Api Service from HomeController

您正在尝试调用一个实例方法,如静态方法。为了访问Get方法,您必须实例化UsersService:

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();
    }
  }