连接API控制器和服务层

本文关键字:服务 控制器 API 连接 | 更新日期: 2023-09-27 18:06:27

我正在尝试使用api控制器-我将其连接到服务层以返回结果并在设置上遇到一些麻烦。这是我的:

public IEnumerable<RoleUser> GetUsers(int sectionID)
{
    var _role = DataConnection.GetRole<RoleUser>(sectionID, r => new RoleUser
    {
        Name = RoleColumnMap.Name(r),
        Email = RoleColumnMap.Email(r)
    }, resultsPerPage: 20, pageNumber: 1);
    return _role;
}

public partial class RoleView
{
    public RoleView()
    {
        this.Users = new HashSet<RoleUser>();
    }
    public ICollection<RoleUser> Users { get; set; }
}
public class RoleUser
{
    public string Name { get; set; }
    public string Email { get; set; }
}
<<p> Api控制器/strong>我应该连接的RoleUser或RoleView,我怎么能设置我的数据在这里从服务。
public class RoleApiController : ApiController
{
    public RoleUser GetRoleUser(int sectionID)
    {
        if (sectionID != null)
        {
            return new RoleUser
            {
               Name = ,
               Email = 
            };
        }
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}
<<p> 视图/strong>
<div>
Name: <span id="name"></span>
</div>
<div>
    Email: <span id="email"></span>
</div>
<script type ="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type ="text/javascript">
    getRoleUser(9, function (roleUser) {
        $("#name").html(roleUser.Name);
        $("#email").html(roleUser.Email);
    });
    function getRoleUser(id, callback) {
        $.ajax({
            url: "/api/RoleUser",
            data: { id: id },
            type: "GET",
            contentType: "application/json;charset=utf-8",
            statusCod: {
                200: function (roleUser) { callback(roleUser); },
                404: function () { alter("Not Found!"); }
            }
        });
    }
</script>

连接API控制器和服务层

你所需要做的就是在你的控制器中为你的服务类添加一个字段:

public class RoleApiController : ApiController
{
    private RoleService _roleService = new RoleService();
    public RoleUser GetRoleUser(int sectionID)
    {
        if (sectionID != null)
        {
            return _roleService.GetUsers(sectionID);
        }
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}