将api控制器与服务层连接 [英] connecting api controller with service layer

查看:167
本文介绍了将api控制器与服务层连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用api控制器-我正在将其连接到服务层以返回结果,并且在设置时遇到了一些麻烦.这就是我所拥有的:

I am trying to use an api controller - I am connecting it to a service layer to return results and having some trouble with the set up. This is what i have:

服务

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

Api控制器 我应该将RoleUser连接到RoleView还是将其连接到RoleView,以及如何在此处设置数据以从服务中获取数据.

Api Controller Should i be connecting the RoleUser or to the RoleView and how can i set my data in here to get from the service.

public class RoleApiController : ApiController
{
    public RoleUser GetRoleUser(int sectionID)
    {
        if (sectionID != null)
        {
            return new RoleUser
            {
               Name = ,
               Email = 
            };
        }
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

查看

<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>

推荐答案

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

All you need to do is add a field for your service class in your controller:

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

这篇关于将api控制器与服务层连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆