gpt4 book ai didi

c# - 通过 AngularJS 将 JSON 发布到 Asp.net

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:42 25 4
gpt4 key购买 nike

我目前在一个网站上工作只是为了使用 AngularJS 和 ASP.net 的乐趣,这篇文章是一个更笼统的问题,因为我不知 Prop 体如何做,我或多或少想知道最佳实践是什么是。目前我在 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();
}

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

谢谢!

最佳答案

您应该允许 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();
}

关于c# - 通过 AngularJS 将 JSON 发布到 Asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30960966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com