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

标签 c# asp.net json angularjs

我目前在一个网站上工作只是为了使用 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/

相关文章:

c# - 如何使用任务或并行调用以正确的顺序获得翻译结果?

c# - 使用刷新 token 的 C#sharp 身份验证的 Google.Apis 客户端

asp.net - Web表单用户控件事件,需要在页面加载后添加

arrays - 需要 JSON 架构数组

java - ElasticSearch 中的部分类型映射

php - 如何读取 json 响应

c# - 如何在 Sharepoint itemadded 事件中检索查询字符串

c# - 如何创建类的实例并从 Bag 对象(如 session )设置属性

c# - 使用 IIS 的基本身份验证在 WCF 服务中获取用户名

c# - Paypal Adaptive - 支付 API