【问题标题】:Post JSON to Asp.net through AngularJS通过 AngularJS 将 JSON 发布到 Asp.net
【发布时间】:2015-09-06 18:48:54
【问题描述】:

我目前正在开发一个网站,只是为了好玩,使用 AngularJS 和 ASP.net,这篇文章是一个更笼统的问题,因为我不知道究竟如何做到这一点,我或多或少想知道最佳实践是什么是。目前我在Angular中有一个像这样的方法

$scope.submit = function () {
    console.log(JSON.stringify($scope.form));
    $http.post("/post/new", "'" + JSON.stringify($scope.form) + "'").
        success(function (data, status, headers, config) {
            console.log("Success")
            $location.path("/news");
        }).error(function (data, status, headers, config) {
            console.log("Error");
        });
};

然后是我对应的Asp.net代码:

    [HttpPost][Route("New")]
    public IHttpActionResult New([FromBody] string input)
    {
        JObject json = JObject.Parse(input);
        Post p = new Post { Title = (string)json["title"], content = (string)json["content"] };
        db.Posts.Add(p);
        db.SaveChanges();
        return Ok();
    }

但是我不认为这是最佳实践,因为首先我将所有内容作为字符串发送并解析它,还因为如果我的 Title 或 Content 项目有一个 ' 字符,那么程序就会出错。我想知道最好的方法是什么。我相信另一种方法是将我的模型作为参数传递给我的方法,但我想知道除此之外是否还有其他方法可以做到这一点。就像我说的,这不是一个非常具体的问题,我只想知道最佳实践。 (非常感谢您提供一点代码来支持您的回复)

谢谢!

【问题讨论】:

    标签: c# asp.net json angularjs


    【解决方案1】:

    您应该允许 JSON.Net 在管道中而不是在您的方法中为您进行反序列化。此外,只需发布​​对象本身,而不是构建一个 json 字符串

    $scope.submit = function () {
        $http.post("/post/new", $scope.form).
            success(function (data, status, headers, config) {
                console.log("Success")
                $location.path("/news");
            }).error(function (data, status, headers, config) {
                console.log("Error");
            });
    };
    
    [HttpPost][Route("New")]
    public IHttpActionResult New([FromBody] Post input)
    {
        db.Posts.Add(input);
        db.SaveChanges();
        return Ok();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      相关资源
      最近更新 更多