【问题标题】:connecting api controller with service layer将 api 控制器与服务层连接
【发布时间】:2013-03-19 08:55:52
【问题描述】:

我正在尝试使用 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; }
}

API 控制器 我应该连接 RoleUser 还是 RoleView 以及如何在此处设置我的数据以从服务中获取。

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>

【问题讨论】:

  • 你遇到了什么麻烦?
  • @jrummell 设置 api 控制器,使其从服务层获取名称和电子邮件信息 - 上面的 api 控制器。

标签: c# asp.net-mvc json asp.net-web-api


【解决方案1】:

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

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

【讨论】:

  • 现在我收到错误 cannot implicitly convert type system.collections...RoleUser to RoleView - 缺少演员表?
  • 既然您提到它,GetUsers() 方法返回一个集合,但您的 Action 返回一个用户。 sectionIDRoleUser是什么关系?每个sectionID 有很多角色吗?如果是这样,您将不得不修改您的服务层。
  • 我认为我应该使用RoleView 而不是RoleUser
猜你喜欢
  • 2011-05-01
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 2016-05-20
  • 2017-03-28
  • 1970-01-01
相关资源
最近更新 更多