调用AngularJS中的Web服务

时间:2018-10-16 21:32:11

标签: angularjs asp.net-web-api

我正在尝试创建一个简单的Web应用程序,用户需要在其中填写表格,并在单击按钮时将信息发送到数据库。

在VS中,我创建了一个新网站,其中包含一个带有以下脚本的HTML页面:

<body> <!--HTML code here -->
<script>
    var app = angular.module('myApp', ["ngMaterial"]);
    app.controller("controller", function ($scope) {
       // upload is called when a button is clicked (using ng-click)
        $scope.upload = function ($http) {
            var info = {
                first: $scope.FirstName,
                last: $scope.LastName,
                gender: $scope.Gender,
                address: $scope.Address,
                mail: $scope.Mail,
                phone: $scope.Phone
            }
            //var ws = "http://localhost:9810/";
            $http.post(ws + "api/Person",
                JSON.stringify(info))
                .then(function (res) {
                    alert(res) },
                function (err) {
                alert(err)});
        };
    });
</script>

然后,在相同的解决方案下,我创建了一个具有以下Controller的Web API:

namespace WebApplication1.Controllers
{
//[Authorize]
public class PersonController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    public void Post([FromBody]string values)
    {
        Person p = new Person();
        dynamic toJson = JObject.Parse(values);
        p.create(toJson.first, toJson.last, toJson.gender,
            toJson.address, toJson.mail, toJson.phone);          
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

以及以下类别:

namespace WebApplication1.Models
{
public class Person
{
    public string first, last, mail, address, gender;
    public int phone;

    public void create(string first, string last,
        string gender, string address, string mail,
        int phone)
    {
        SqlConnection con = new SqlConnection("server=localhost;uid=sa;database=dbPerson");
        string sqlCmd = "insert into dbPerson values (@first, @last, @gender, @address, @mail, @phone)";
        SqlCommand cmd = new SqlCommand(sqlCmd, con);
        cmd.Parameters.Add(new SqlParameter("@first", first));
        cmd.Parameters.Add(new SqlParameter("@last", last));
        cmd.Parameters.Add(new SqlParameter("@gender", gender));
        cmd.Parameters.Add(new SqlParameter("@address", address));
        cmd.Parameters.Add(new SqlParameter("@mail", mail));
        cmd.Parameters.Add(new SqlParameter("@phone", phone));
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
    }
}

我的问题是我可以在哪里托管此Web API?我可以将其托管在笔记本电脑的本地服务器上吗?

0 个答案:

没有答案