为什么邮递员返回“非静态方法需要目标”。

时间:2016-08-22 15:13:21

标签: c# linq entity-framework-6 asp.net-mvc-5.2 .net-4.6

我的savedController(Web Api控制器)中有一个Save方法。当我用邮递员测试它时它返回了它。

    {
"message": "An error has occurred.",
"exceptionMessage": "Non-static method requires a target.",
"exceptionType": "System.Reflection.TargetException",
"stackTrace": "   at System.Web.Http.ApiController.    <InvokeActionWithExceptionFilters>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
  }

我的保存方法就是这个。 if语句

引发了异常
[HttpPost]
public IHttpActionResult Save(SavesDto dto)
{
    var userId = User.Identity.GetUserId();

    if (_context.SavedPosts.Any(a => a.AttendeeId == userId && a.PostId == dto.PostId))
    return BadRequest("The save already exists.");

    var savedPost = new Saves
    {
        PostId = dto.PostId,
        AttendeeId = userId
    };
    _context.SavedPosts.Add(savedPost);
    _context.SaveChanges();

    return Ok();
}

我在互联网上搜索过。我发现问题来自在LINQ中使用空值。但Linq语句中的任何方法只返回true / false,为什么会抛出此异常?

    public class SavesDto
{
    public int PostId { get; set; }
}

我在这里打电话给Api

@foreach(var post in Model)
{
<button
 data-post-id="@post.Id" 
class="btn btn-default btn-sm pull-right .js-toggle-save">Save ?</button
}

@section scripts
{
  <script>
$(document).ready(function()
{
    $(".js-toggle-save").click(function(e)
    {
        var button = $(e.target);
        $.post("/api/saves", { postId: button.attr("data-post-id") } )
        .done(function()
        {
            button.removeClass("btn-default")
            .addClass("btn-info").text("Saved");
        })
        .fail(function ()
        {
            alert("something failed");
        })
    });
}
);
</script>
}

PostId和AttendeeId不可为空

public class Saves
{
    public ApplicationUser User { get; set; }
    public Post Post { get; set; }

    [Key]
    [Column(Order = 1)]
    public int PostId { get; set; }

    [Key]
    [Column(Order = 2)]
    public string AttendeeId { get; set; }

}

1 个答案:

答案 0 :(得分:0)

在lambda表达式中使用null的变量时会发生此异常。似乎dto对象为null。所以试着这样做:

if (dto != null && _context.SavedPosts.Any(a => a.AttendeeId == userId
  && a.PostId == dto.PostId))