• [入门一]C# webApi创建、与发布、部署、api调用


    一.创建web api项目

    1.1、项目创建

    MVC架构的话,它会有view-model-control三层,在web api中它的前端和后端是分离的,所以只在项目中存在model-control两层

    1.2、修改路由

    打开App_Start文件夹下,WebApiConfig.cs ,修改路由,加上{action}/ ,这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数,冲突。其中,{id}是api接口函数中的参数。
     

    默认路由配置信息为:【默认路由模板无法满足针对一种资源一种请求方式的多种操作。】
    WebApi的默认路由是通过http的方法(get/post/put/delete)去匹配对应的action,也就是说webapi的默认路由并不需要指定action的名称

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web.Http;
    5. namespace WebAPI
    6. {
    7. public static class WebApiConfig
    8. {
    9. public static void Register(HttpConfiguration config)
    10. {
    11. // Web API 配置和服务
    12. // Web API 路由
    13. config.MapHttpAttributeRoutes();
    14. config.Routes.MapHttpRoute(
    15. name: "DefaultApi",
    16. //修改路由,加上{action}/ ,这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,
    17. //否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数,冲突。其中,{id}是api接口函数中的参数
    18. routeTemplate: "api/{controller}/{action}/{id}",
    19. defaults: new { id = RouteParameter.Optional }
    20. );
    21. }
    22. }
    23. }

    二.测试案例

    写一个测试的api函数,并开始执行(不调试)

    2.1、我们在model文件夹中添加一个类movie

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. namespace WebAPI.Models
    6. {
    7. public class movie
    8. {
    9. public string name { get; set; }
    10. public string director { get; set; }
    11. public string actor { get; set; }
    12. public string type { get; set; }
    13. public int price { get; set; }
    14. }
    15. }

    2.1.2、我们在model文件夹中添加一个类Product

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. namespace WebAPI.Models
    6. {
    7. public class Product
    8. {
    9. public int Id { get; set; }
    10. public string Name { get; set; }
    11. public string Category { get; set; }
    12. public decimal Price { get; set; }
    13. }
    14. }

    2.2、在controller文件夹下添加web api控制器,命名改为TestController

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Net;
    5. using System.Net.Http;
    6. using System.Web.Http;
    7. using WebAPI.Models;
    8. namespace WebAPI.Controllers
    9. {
    10. public class TestController : ApiController
    11. {
    12. movie[] mymovie = new movie[]
    13. {
    14. new movie { name="海蒂和爷爷",director="阿兰.葛斯彭纳",actor="阿努克",type="动漫",price=28},
    15. new movie { name="云南虫谷",director="佚名",actor="潘粤明",type="惊悚",price=32},
    16. new movie { name="沙海",director="佚名",actor="吴磊",type="惊悚",price=28},
    17. new movie { name="千与千寻",director="宫崎骏",actor="千寻",type="动漫",price=28}
    18. };
    19. public IEnumerable GetAllMovies()
    20. {
    21. return mymovie;
    22. }
    23. public IHttpActionResult GetMovie(string name) //异步方式创建有什么作用
    24. {
    25. var mov = mymovie.FirstOrDefault((p) => p.name == name);
    26. if (mymovie == null)
    27. {
    28. return NotFound();
    29. }
    30. return Ok(mymovie);
    31. }
    32. }
    33. }

    这样就完成了一个web api实例的编写

    2.2.2、在controller文件夹下添加web api控制器,命名改为productsController

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Net;
    5. using System.Net.Http;
    6. using System.Web.Http;
    7. using WebAPI.Models;
    8. namespace WebAPI.Controllers
    9. {
    10. public class productsController : ApiController
    11. {
    12. Product[] products = new Product[]
    13. {
    14. new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
    15. new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
    16. new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
    17. };
    18. public IEnumerable GetAllProducts()
    19. {
    20. return products;
    21. }
    22. public IHttpActionResult GetProduct(int id)
    23. {
    24. var product = products.FirstOrDefault((p) => p.Id == id);
    25. if (product == null)
    26. {
    27. return NotFound();
    28. }
    29. return Ok(product);
    30. }
    31. }
    32. }

    2.2.3、在controller文件夹下添加web api控制器,命名改为MyController

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Net;
    5. using System.Net.Http;
    6. using System.Web.Http;
    7. namespace WebAPI.Controllers
    8. {
    9. public class MyController : ApiController
    10. {
    11. [HttpGet]
    12. public string MyExample(string param1, int param2)
    13. {
    14. string res = "";
    15. res = param1 + param2.ToString();
    16. //这边可以进行任意操作,比如数据存入或者取出数据库等
    17. return res;
    18. }
    19. }
    20. }

    三.本地调试

    3.1 运行调试,以本地 localhost(或127.0.0.1)形式访问
    ①点击工具栏【IIS Express】

    ②浏览地址输入接口,看是否可以访问

    localhost:44381/api/products/GetAllProducts

    注意:

    这里的路径是写你的控制器前缀名称(Control文件下的productsController控制器文件的前缀)

    https://localhost:44381/api/Test/GetAllMovies

    2)直接在浏览器中调试也行

    想要调试的值,可以将WebApiConfig.cs的代码修如下

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web.Http;
    5. namespace WebAPI
    6. {
    7. public static class WebApiConfig
    8. {
    9. public static void Register(HttpConfiguration config)
    10. {
    11. // Web API 配置和服务
    12. // Web API 路由
    13. config.MapHttpAttributeRoutes();
    14. config.Routes.MapHttpRoute(
    15. name: "DefaultApi",
    16. //修改路由,加上{action}/ ,这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,
    17. //否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数,冲突。其中,{id}是api接口函数中的参数
    18. routeTemplate: "api/{controller}/{action}/{id}",
    19. defaults: new { id = RouteParameter.Optional }
    20. );
    21. //去掉xml返回格式、设置json字段命名采用
    22. var appXmlType =
    23. config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
    24. config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    25. }
    26. }
    27. }

    ok,显示成功

    localhost:44381/api/My/MyExample?param1=¶m2=2

    WebApi项目实例3-1

    3-1 (1)新添加到控制器UserInfoController,

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Net;
    5. using System.Net.Http;
    6. using System.Web.Http;
    7. using WebAPI.Models;
    8. namespace WebAPI.Controllers
    9. {
    10. public class UserInfoController : ApiController
    11. {
    12. //检查用户名是否已注册
    13. private ApiTools tool = new ApiTools();
    14. // [HttpPost]
    15. [HttpGet]
    16. public HttpResponseMessage CheckUserName(string _userName)
    17. {
    18. int num = UserInfoGetCount(_userName);//查询是否存在该用户
    19. if (num > 0)
    20. {
    21. return tool.MsgFormat(ResponseCode.操作失败, "不可注册/用户已注册", "1 " + _userName);
    22. }
    23. else
    24. {
    25. return tool.MsgFormat(ResponseCode.成功, "可注册", "0 " + _userName);
    26. }
    27. }
    28. private int UserInfoGetCount(string username)
    29. {
    30. //return Convert.ToInt32(SearchValue("select count(id) from userinfo where username='" + username + "'"));
    31. return username == "admin" ? 1 : 0;
    32. }
    33. }
    34. }

    添加返回(响应)类ApiTools

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Net.Http;
    5. using System.Text.RegularExpressions;
    6. using System.Web;
    7. namespace WebAPI.Models
    8. {
    9. //添加返回(响应)类
    10. public class ApiTools
    11. {
    12. private string msgModel = "{{\"code\":{0},\"message\":\"{1}\",\"result\":{2}}}";
    13. public ApiTools()
    14. {
    15. }
    16. public HttpResponseMessage MsgFormat(ResponseCode code, string explanation, string result)
    17. {
    18. string r = @"^(\-|\+)?\d+(\.\d+)?$";
    19. string json = string.Empty;
    20. if (Regex.IsMatch(result, r) || result.ToLower() == "true" || result.ToLower() == "false" || result == "[]" || result.Contains('{'))
    21. {
    22. json = string.Format(msgModel, (int)code, explanation, result);
    23. }
    24. else
    25. {
    26. if (result.Contains('"'))
    27. {
    28. json = string.Format(msgModel, (int)code, explanation, result);
    29. }
    30. else
    31. {
    32. json = string.Format(msgModel, (int)code, explanation, "\"" + result + "\"");
    33. }
    34. }
    35. return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
    36. }
    37. }
    38. public enum ResponseCode
    39. {
    40. 操作失败 = 00000,
    41. 成功 = 10200,
    42. }
    43. }

    3-1 (2)本地调试,调用Web API接口

    运行调试,以本地 localhost(或127.0.0.1)形式访问
    ①点击工具栏【IIS Express】

    ②浏览地址输入接口,看是否可以访问

    https://localhost:44381/api/UserInfo/CheckUserName?_userName=wxd

    3.2 运行调试,以本地IP(192.168.6.152)形式访问
    127.0.0.1是回路地址,来检验本机TCP/IP协议栈,实际使用过程中服务端不在本机,是外部地址,要用IP地址测试。
    外部用户采用IP+端口号访问,如下图浏览器访问不了,400错误。
     

    解决方案:

    因为 IIS 7 采用了更安全的 web.config 管理机制,默认情况下会锁住配置项不允许更改。

    以管理员身份运行命令行【此处不要操作】

    C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers

    如果modules也被锁定,再运行

    C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/modules

    客户端程序:调用接口分为以下几种情况:
    通过Javascript 和 jQuery 调用 Web API
    右键资源管理器解决方案下面的项目,添加-新建项

    将index.html内容替换成:

    1. html>
    2. <html xmlns="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <title>Product Apptitle>
    5. head>
    6. <body>
    7. <div>
    8. <h2>All Productsh2>
    9. <ul id="products" />
    10. div>
    11. <div>
    12. <h2>Search by IDh2>
    13. <input type="text" id="prodId" size="5" />
    14. <input type="button" value="Search" onclick="find();" />
    15. <p id="product" />
    16. div>
    17. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js">script>
    18. <script>
    19. var uri = 'api/Products';
    20. $(document).ready(function () {
    21. // Send an AJAX request
    22. $.getJSON(uri)
    23. .done(function (data) {
    24. // On success, 'data' contains a list of products.
    25. $.each(data, function (key, item) {
    26. // Add a list item for the product.
    27. $('
    28. ', { text: formatItem(item) }).appendTo($('#products'));
  • });
  • });
  • });
  • function formatItem(item) {
  • return item.Name + ': $' + item.Price;
  • }
  • function find() {
  • var id = $('#prodId').val();
  • $.getJSON(uri + '/' + id)
  • .done(function (data) {
  • $('#product').text(formatItem(data));
  • })
  • .fail(function (jqXHR, textStatus, err) {
  • $('#product').text('Error: ' + err);
  • });
  • }
  • script>
  • body>
  • html>
  • 四.发布web api 并部署

    4.1、首先,右键项目,选择发布:

    到这里,程序已经发布到指定的路径下了(这里的路径,可以是本机的文件夹,也可以是服务器上的ftp路径)

    4.2、我们还剩最后一步,就是,在IIS上,把发布的服务端程序挂上去,不说了,直接上图:
    打开iis,选中网站,右键 添加网站, 

     好了,服务端程序发布并部署完成。

    这个WebAPI就是刚刚我们部署好的,点击下图右侧的浏览*91(http),会打开网页

  • 相关阅读:
    全志R128外设模块配置——PMU电源管理
    云耀服务器L实例搭配负载均衡部署Linux 可视化宝塔面板
    VBA-自定义面板,使用SQL查询Excel数据
    【左程云算法全讲13】暴力递归
    linux配置java-web站点
    Navicat DML 操作
    【Shell 脚本速成】07、Shell 流程控制——if 判断语句
    【21天学习挑战赛】冒泡排序
    计算机视觉面试题整理
    软件测试相关知识
  • 原文地址:https://blog.csdn.net/zgscwxd/article/details/133823295