繁体   English   中英

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

[英]Why the postman is returning a “Non-static method requires a target.”

我的SavesController(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; }
}

我在这里叫阿皮

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

}

当您在lambda表达式中使用变量为空时,会发生此异常。 看来dto对象为null。 因此,尝试这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM