connecting api controller with service layer

╄→尐↘猪︶ㄣ 提交于 2019-12-25 04:09:38

问题


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:

Service

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

Model

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

View

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

回答1:


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


来源:https://stackoverflow.com/questions/15689989/connecting-api-controller-with-service-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!