c# - 无法使用 AngularJs 和 C# WebService 后端将数据插入 PostgreSql

标签 c# asp.net angularjs postgresql

我是 angularjs 的新手,我创建了 HTML 文件并将 Controller 传递给 RegistrationController.js,我创建了 Registration.cs 文件来存储和检索来自数据库的数据。问题是,我没有收到任何错误,没有得到输出,我无法识别我在代码中犯的错误。

RegisterController.js

    var app = angular.module("app", []) 
    app.controller("RegisterController", function ($scope, $http) {
        $scope.firstname = "";
        $scope.lastname = "";
        $scope.email = "";
        $scope.password = "";
        $scope.address = "";
        $scope.save = function () {
            var httpreq = {
                method: 'POST',
                url: 'http://localhost:50361/Registration.aspx',
                headers: {
                    'Content-Type':'application/json; charset=utf-8',
                    'dataType': 'json'
                },               
                data: {
                    firstname: $scope.firstname,
                    lastname: $scope.lastname,
                    email: $scope.email,
                    password: $scope.password,
                    address: $scope.address
                }
            };
            $http(httpreq).then(function (response) {

                alert("Registered Successfully");

            })
            .catch(function (error) {});
        }
    });

Registration.cs

public class Registration : System.Web.Services.WebService
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string email { get; set; }
    public string password { get; set; }
    public string address { get; set; }

    [WebMethod]
    public string InsertRegistration(string firstname, string lastname,
            string email, string password, string address)
    {
       NpgsqlConnection con = new NpgsqlConnection("Server=10.0.5.22;Port=5432;Database=TEST_DB;User Id=postgres;Password=test;");
        try
        {
            con.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("insert into Registration1(FirstName,LastName,Email,Password,Address)values('" + firstname + "','" + lastname + "','" + email + "','" + password + "','" + address + "')", con);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            con.Close();
            return "Record Inserted Successfully";
        }
        }}

最佳答案

当您创建 asmx Web 服务时,您会得到两个文件:

  • 一个.asmx定义端点的文件
  • 一个.cs包含“代码隐藏”和 WebMethod 的文件定义。

您的 ajax 客户端必须指向 .asmx端点,而不是 .cs文件,例如

http://localhost/MyApp/Registration.asmx/InsertRegistration

此外,我认为还有一些问题需要指出:

  • 您需要用 [System.Web.Script.Services.ScriptService] 修饰服务为了将它与 Ajax 一起使用。
    • 无论如何.asmx Web 服务是遗留技术(它们用于 xml SOAP)- 为了公开 RESTful 服务以供 Angular 等现代前端使用,您应该使用 Asp.net WebApi 2 或更高版本。
    • 不要使用字符串连接将变量绑定(bind)到 SqlCommand - 这会使您的数据库容易受到 SqlInjection 攻击。像我上面做的那样参数化它们
    • 不要以明文形式存储密码。 Add a salt and hash many times
    • 对于 Postgres,要非常小心大小写 - PostGres 区分大小写,但前提是您将标识符包装在 double quotes (") 中。 , 因此通篇使用小写字母通常更安全。
    • 您错过了您的 catchfinally平衡您的声明 try
    • SqlCommand这样包装一次性用品会更安全和 SqlConnectionusing阻止
    • 除非您的 Web 服务是有状态的(这不是一个可扩展的想法),否则您不应该拥有可公开访问的属性 public string firstname { get; set; }等等 - 这些在您的注册中不需要并且与传递的参数冲突。

决赛WebMethod .cs看起来更像这样:

[System.Web.Script.Services.ScriptService]
public class Registration : WebService
{
    [WebMethod]
    public string InsertRegistration(string firstname, string lastname,
                string email, string password, string address)
    {
        try
        {
            using (var con = new NpgsqlConnection(
         "Server=127.0.0.1;Port=5432;Database=TEST_DB;User Id=user;Password=password;"))
            using (var cmd = new NpgsqlCommand(
       "insert into public.registration1(firstname, lastname, email, passwordhash, address)"
             + " values (@firstName, @lastName, @email, @passwordhash, @address);", con))
            {
                con.Open();
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@firstName", firstname);
                cmd.Parameters.AddWithValue("@lastName", lastname);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@passwordhash", HashMyPassword(password));
                cmd.Parameters.AddWithValue("@address", address);
                cmd.ExecuteNonQuery();
            }
            return "Record Inserted Successfully";
        }
        catch (Exception)
        {
            return "Failed";
        }
    }

    public static string HashMyPassword(string unhashed)
    {
       // use a decent hashing algo like PBKDF2 or scrypt
    }
}

以及关联的端点标记文件,Registration.asmx简直就是

<%@ WebService Language="C#" CodeBehind="Registration.asmx.cs" Class="MyNameSpace.Registration" %>

关于c# - 无法使用 AngularJs 和 C# WebService 后端将数据插入 PostgreSql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47524006/

相关文章:

c# - Unity中角色跳跃时如何禁用重力?

c# - 在 MVC 中存储/调用重复代码块

c# - 子网掩码的正则表达式?

c# - 我可以用什么来 asp.net 存储工具提示消息?

javascript - ESlint 编译 es6 导入/导出语句失败

c# - C# 或 SQL 中的隔离级别 - 将使用哪一个?

c# - 将 Web API Controller 端点添加到 Kestrel 工作程序项目

c# - GridView:隐藏标题上的排序箭头

javascript - 在 AngularJS 中使用 Promises 的 $http 调用的条件链接

javascript - 如何防止在一条路由中启动的慢速 $http 在用户更改路由后可能解析?