【C#】MVC调用WebApi的Demo

MVC调用WebApi的Demo
文章目录
MVC调用WebApi的Demo
目的
WebApi项目
链接:https://blog.csdn.net/unclebober/article/details/86649800
MVC调用WebApi
项目代码:https://blog.csdn.net/unclebober/article/details/86674098
遇到的问题
1.如何将请求的数据以JSON格式返回
参考链接:https://www.cnblogs.com/zkwarrior/p/4734684.html
2.Post请求需要在传参时加上[FromBody]
3.使用HttpClientExtensions方法[PostAsJsonAsync(HttpClient, String, T)]
4.Delete操作报错
5.Add,Update,Delete等Post请求的参数传递
6.HttpClient.PostAsJsonAsync 方法无法调用
7.[HttpGet],[HttpPost]等标签的使用
目的
通过MVC项目调用写好的Api,完成数据库增删改查操作

WebApi项目
链接:https://blog.csdn.net/unclebober/article/details/86649800
MVC调用WebApi
项目代码:https://blog.csdn.net/unclebober/article/details/86674098
遇到的问题
1.如何将请求的数据以JSON格式返回
当客户端调用某个Action方法并希望以JSON的格式返回请求的数据时,ASP.NET MVC需要有一种机制将CLR对象转换成JSON格式予以响应,而这可以通过JsonResult来解决。

参考链接:https://www.cnblogs.com/zkwarrior/p/4734684.html
// GET api/values
        /// <summary>
        /// 客户端调用某个Action方法并希望以JSON的格式返回请求的数据,使用JsonResult
        /// </summary>
        /// <returns></returns>
        public /*string*/JsonResult<List<User>> GetAll()
        {
            List<User> userInfoList = new List<User>();
            SqlConnection conn = new SqlConnection(constr);
            string text = "userinfo_get";
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(text, conn);
            DataSet ds = new DataSet("Students");
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
            foreach (DataRow row in dt.Rows)
            {
                User user = new Models.User();
                user.Id = Convert.ToInt16(row["Id"]);
                user.Name = Convert.ToString(row["Name"]);
                user.Sex = Convert.ToString(row["Sex"]);
                user.Age = Convert.ToInt16(row["Age"]);

                userInfoList.Add(user);
            }
            conn.Close();
            return Json<List<User>>(userInfoList);
            ///xml不可行
            //XmlSerializer serializer = new XmlSerializer(typeof(List<User>));
            //return serializer.Serialize(userInfoList);
            
            //return JsonConvert.SerializeObject(userInfoList);
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2.Post请求需要在传参时加上[FromBody]
另外我们可以注意到在Post Put的方法参数有一个关键字[ FromBody ],而Get、Delete则没有。,事实上没有加[ FromBody ]就默认为[ FromUri ].

3.使用HttpClientExtensions方法[PostAsJsonAsync(HttpClient, String, T)]
使用前需要安装Microsoft.AspNet.WebApi.Client扩展

4.Delete操作报错


代码:

[HttpPost]
public async Task<ActionResult> DelInfo1(int id)
{
    client.BaseAddress = new Uri("http://10.194.46.143:5533/api/values/delete");
    //var respones = await client.GetStringAsync(client.BaseAddress);
    //HttpContent content = new HttpContent()
    var response = await client.PostAsJsonAsync(client.BaseAddress,id);
    return View();
}
1
2
3
4
5
6
7
8
9
解决措施:删除[HttpPost]即可

5.Add,Update,Delete等Post请求的参数传递
由于Post请求不能通过地址栏来传递参数,所以需要在方法中加上[FromBody]。而FromBody只能传递一个参数,因此定义一个类(包含四个属性Id,Name,Sex,Age),通过传递类,将四个参数传过来。

public async Task<ActionResult> UpdateInfo1(int id,string UserName,string UserSex,int UserAge)
        {
            client.BaseAddress = new Uri("http://10.194.46.143:5533/api/values/update");
            Para para = new Para
            {
                Id = id,
                Name = UserName,
                Sex = UserSex,
                Age = UserAge

            };
            //将Post请求发送给指定URI
            var response = await client.PostAsJsonAsync(client.BaseAddress,para);
            return View();
        }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
对应api

         [HttpPost]
        // PUT api/values/5
        public void Update([FromBody]Para para)
        {
            SqlConnection conn = new SqlConnection(constr);
            string text = "userinfo_update";
            SqlParameter[] updatepara =
            {
                new SqlParameter("@id",para.Id),
                new SqlParameter("@name",para.Name),
                new SqlParameter("@sex",para.Sex),
                new SqlParameter("@age",para.Age)
            };
            SqlCommand cmd = new SqlCommand(text, conn);
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in updatepara)
            {
                if (parameter != null)
                    cmd.Parameters.Add(parameter);
                else
                    continue;
            }
            conn.Open();    //Open the sql
            cmd.ExecuteNonQuery();
            conn.Close();
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
6.HttpClient.PostAsJsonAsync 方法无法调用
需要安装Microsoft.AspNet.WebApi.Client扩展

7.[HttpGet],[HttpPost]等标签的使用
先看一段代码

从上面的例子可以看出在Action中没有使用[HttpGet]、[HttpPost] 等修饰,这是什么情况呢?

Action 皆以HTTP 动词开头Get、Post、Put、Delete ,这个也是刚好符合 webapi的约定的,什么约定呢?

你调用什么类型的方法 ,例如 post 方法,那么他就去 你的所有的 action 里面 去找 以 post 开头的方法 ,名字可以随便叫,例如 postToDataBase 等等,只要开头匹配 就可以了

打个比喻,假设今天服务端收到了一个GET 请求时,会去查找对应的Controller 并且Action 以"Get…" 开头的方法,举个例子:GetMembers、GetTime,以此类推,如果我们从jQuery Ajax 发出了一个POST 请求,也会自动对应到以"Post…" 开头的Action 内,也就是说实际呼叫哪个Controller 的Action 不是利用网址来决定,而是依照HTTP 所送出的请求来决定,这也就是非常典型的REST风格,而在Web API 中也处理了回传的数据,让我们看看Get() 这个方法,回传IEnumerable 的方法,等于我们拥有了强类型。
如果说我们使用的方法名称不是 Get/Post/Put/Delete 的规则时,那么我们就一定要宣告它的接受动词 (Accept Verb),所以我们可以

修改如下代码:

————————————————
版权声明:本文为CSDN博主「iam_Cheng」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/unclebober/article/details/86649988

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值