ASP.Net核心WebAPI控制器 - 200状态代码但没有响应

时间:2017-05-30 20:22:28

标签: asp.net-core asp.net-core-webapi

我的网络API中有以下控制器:

[Route("api/[controller]")]
public class User_TaskController : Controller
{
    private readonly IUser_TaskRepository _taskRepository;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly WebAPIDataContext _context;

    //Controller
    public User_TaskController(IUser_TaskRepository taskRepository, UserManager<ApplicationUser> userManager, WebAPIDataContext context)
    {
        _taskRepository = taskRepository;
        _userManager = userManager;
        _context = context;
    }

    //Get methods
    [HttpGet]
    public IEnumerable<User_Task> GetAll()
    {

        return _taskRepository.GetAll();
    }


    [Authorize]
    [HttpGet("current")]
    public IActionResult GetCurrentUserTasks()
    {

        // Obtain stakeholderId
        var stakeholderId = this.GetStakeholderId();
        var userTasks = _taskRepository.GetUserTasks(stakeholderId);

        return new ObjectResult(userTasks);
    }

    [HttpGet("{id}", Name = "GetTask")]
    public IActionResult GetById(long id)
    {
        var item = _taskRepository.Find(id);
        if (item == null)
        {
            return NotFound();
        }
        return new ObjectResult(item);
    }

    //Create
    [Authorize]
    [HttpPost]
    public IActionResult Create([FromBody] User_Task item)
    {

        if (item == null)
        {
            return BadRequest();
        }

        var stakeholderId = this.GetStakeholderId();


        _taskRepository.Add(item, stakeholderId);

        var itemToReturn = _taskRepository.Find(item.TaskId);
        if (item == null)
        {
            return NotFound();
        }
        return new ObjectResult(itemToReturn);

    }

    private long GetStakeholderId()
    {
        string currentUserId = _userManager.GetUserId(User);
        long stakeholderId = 0;

        var users = _userManager.Users;
        foreach (var user in users)
        {
            if (user.Email == currentUserId)
            {
                var idForStakeholder = user.Id;
                var stakeholders = _context.Stakeholders;
                foreach (var stakeholder in stakeholders)
                {
                    if (stakeholder.IdentityId == idForStakeholder)
                    {
                        stakeholderId = stakeholder.StakeholderId;
                        return stakeholderId;
                    }
                }

            }
        }
        return stakeholderId;
    }

}

相应的存储库:

public class User_TaskRepository : IUser_TaskRepository
{
    private readonly WebAPIDataContext _context;

    public User_TaskRepository(WebAPIDataContext context)
    {
        _context = context;

    }

    public IEnumerable<User_Task> GetAll()
    {
        return _context.User_Tasks.Include(task => task.Steps).ToList();
    }

    // Method that returns all the tasks of a specific user i.e. logged in used making the request
    public ICollection<User_Task> GetUserTasks(long stakeholderId)
    {

        var userTasks = _context.User_Tasks
            .Where(task => task.StakeholderId == stakeholderId).ToList();

        return userTasks;
    }

    public void Add(User_Task item , long stakeholderId)
    {
        item.StakeholderId = stakeholderId;   

       _context.User_Tasks.Add(item);
       _context.SaveChanges();
    }

    public User_Task Find(long key)
    {
        return _context.User_Tasks.Include(task => task.Steps).FirstOrDefault(t => t.TaskId == key);
    }


}

public interface IUser_TaskRepository
{
    void Add(User_Task item, long stakeholderId);
    IEnumerable<User_Task> GetAll();
    ICollection<User_Task> GetUserTasks(long stakeholderId);
    User_Task Find(long key);
}

问题

  1. 对于create方法,记录会添加到数据库中,但我在Postman中没有得到任何响应。
  2. 为了获取特定用户的任务,即GetCurrentUserTasks()直到return语句之前的最后一行,我看到获取的任务但是它什么也没有返回,我仍然在我的angular2前端获得状态200 Ok。我尝试删除[授权]标题但没有效果。
  3. 为什么会这样?

2 个答案:

答案 0 :(得分:0)

由于您使用ObjectResult(){},我相信内联更改正是您所寻找的。

[Authorize]
[HttpGet("current")]
public IActionResult GetCurrentUserTasks()
{
    var status = HttpStatus.Ok; //<< add

    // Obtain stakeholderId
    var stakeholderId = this.GetStakeholderId();
    var userTasks = _taskRepository.GetUserTasks(stakeholderId);

    if(userTasks == null)
       status = HttpStatusCode.NoContent;

    return new ObjectResult(userTasks){StatusCode = (int)status };
}

包含更改的方法下方

//Create
[Authorize]
[HttpPost]
public IActionResult Create([FromBody] User_Task item)
{
   var status = HttpStatusCode.Ok;
    if (item == null)
    {
        status = HttpStatusCode.BadRequest;
        return BadRequest();
    }

    var stakeholderId = this.GetStakeholderId();


    _taskRepository.Add(item, stakeholderId);

    var itemToReturn = _taskRepository.Find(item.TaskId);
    if (itemToReturn == null)
    {
        status = HttpStatusCode.NoContent;
        return NotFound();
    }
    return new ObjectResult(itemToReturn){StatusCode = (int)status};

}

现在GetCurrentUserTasks()方法没有做你期望的等同_userManager.GetUserId(User);返回用户的ID,这是一个GUID而不是电子邮件,因此你在for循环中是逻辑的(为什么你通过用户循环,是一个不寻常的步骤,真的无用)杀死下一个循环结构。这完全基于我假设您正在为ASp.net Core使用未经改变的身份设置。

private long GetStakeholderId()
{
    string currentUserId = _userManager.GetUserId(User);  // << GUID
    long stakeholderId = 0;

    var users = _userManager.Users;       //<< pointless
    foreach (var user in users)           //   ^^^   
    {
        if (user.Email == currentUserId)  << // will never be TRUE
        {
            var idForStakeholder = user.Id;
            var stakeholders = _context.Stakeholders;
            foreach (var stakeholder in stakeholders)
            {
                if (stakeholder.IdentityId == idForStakeholder)
                {
                    stakeholderId = stakeholder.StakeholderId;
                    return stakeholderId;
                }
            }

        }
    }
    return stakeholderId;   // WILL ALWAYS be 0
}

我很确定此时从发布的代码中你将从GetCurrentUserTasks()获得OK 200,因为它确实运行但从未为用户提取任务,因为用户实际上从未真正在基础中找到你的代码

答案 1 :(得分:0)

对于你的Create()方法,似乎你正在检查“item”变量是否为null,然后返回“itemToReturn”变量,该变量可能为null(这就是为什么你得到一个空结果): / p>

   //Create
    [Authorize]
    [HttpPost]
    public IActionResult Create([FromBody] User_Task item)
    {

        if (item == null)
        {
            return BadRequest();
        }

        var stakeholderId = this.GetStakeholderId();


        _taskRepository.Add(item, stakeholderId);

        var itemToReturn = _taskRepository.Find(item.TaskId);
        if (item == null) // checking item instead of itemToReturn
        {
            return NotFound();
        }
        return new ObjectResult(itemToReturn);

    }

你不应该检查“itemToReturn”是否为空?