webapi测试例子

 

1. 修改WebApiConfig.cs中路由路径

    问题:webapi的默认路由并不需要指定action的名称(WebApi的默认路由是通过http的方法get/post/put/delete去匹配对应的action),

               但默认路由模板无法满足针对一种资源一种请求方式的多种操作。

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

 View Code

 

2. 添加控制器
    a. 右键Controllers文件夹---添加---控制器)

    b. 左边选择web API页签,右边选择控制器(空)

     c. 给控制器命名(只需要改高亮部分,后面的Controller保留)

 3. 功能测试

    a. 右键Models文件夹,选择新建类

复制代码
public class Game
    {
        public string name { get; set; }
        public string director { get; set; }
        public string actor { get; set; }
        public string type { get; set; }
        public int price { get; set; }
    }

 public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
View Code
复制代码

    b. 右键Controllers文件夹,增加控制器

复制代码
 public class TestController : ApiController
    {
        Game[] myGame = new Game[]
        {
            new Game { name="one",director="one.1",actor="a",type="动漫",price=28},
            new Game { name="two",director="two.1",actor="b",type="惊悚",price=32},
            new Game { name="three",director="three.1",actor="c",type="惊悚",price=28},
            new Game { name="four",director="four.1",actor="d",type="动漫",price=28}
        };
        public IEnumerable<Game> GetAllMovies()
        {
            return myGame;
        }
        public IHttpActionResult GetMovie(string name)    //异步方式创建有什么作用
        {
            var mov = myGame.FirstOrDefault((p) => p.name == name);
            if (myGame == null)
            {
                return NotFound();
            }
            return Ok(myGame);
        }
    }



 public class ProductsController : ApiController
    {
        Product[] products = new Product[]
        {
            new Product { Id = 1, Name = "Apple Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 4.35M },
            new Product { Id = 3, Name = "Linda", Category = "Hardware", Price = 11.2M }
        };
        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }


 public class ParaController : ApiController
    {
        [HttpGet]
        public string ParaExample(string param1, int param2)
        {
            string res = "";
            res = param1 + param2.ToString();
            //其他操作
            return res;
        }
    }
View Code
复制代码

    c. 点击运行,在URL后加具体action路径

结果如下:

d. 去掉xml返回格式、设置json返回

复制代码
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            // Web API 路由
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                //修改路由,加上{action}/ ,这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,
                //否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数,冲突。其中,{id}是api接口函数中的参数
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //去掉xml返回格式、设置json字段命名采用
            var appXmlType =
                config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        }
    }
修改WebApiConfig.cs
复制代码

 

     e. 统一返回值格式

复制代码
 public class RtnValue
    {
        private string msgModel = "{{\"code\":{0},\"message\":\"{1}\",\"result\":{2}}}";
        public RtnValue()
        {
        }
        public HttpResponseMessage MsgFormat(ResponseCode code, string explanation, string result)
        {
            string r = @"^(\-|\+)?\d+(\.\d+)?$";
            string json = string.Empty;
            if (Regex.IsMatch(result, r) || result.ToLower() == "true" || result.ToLower() == "false" || result == "[]" || result.Contains('{'))
            {
                json = string.Format(msgModel, (int)code, explanation, result);
            }
            else
            {
                if (result.Contains('"'))
                {
                    json = string.Format(msgModel, (int)code, explanation, result);
                }
                else
                {
                    json = string.Format(msgModel, (int)code, explanation, "\"" + result + "\"");
                }
            }
            return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
        }
    }
    public enum ResponseCode
    {
        操作失败 = 00000,
        操作成功 = 10000,
    }



 public class CheckController : ApiController
    {
        //检查用户名是否已注册
        private RtnValue tool = new RtnValue();
        [HttpGet]
        public HttpResponseMessage CheckUserName(string _userName)
        {
            int num = UserInfoGetCount(_userName);//查询是否存在该用户
            if (num > 0)
            {
                return tool.MsgFormat(ResponseCode.操作失败, "不可注册/用户已注册", "1 " + _userName);
            }
            else
            {
                return tool.MsgFormat(ResponseCode.操作成功, "可注册", "0 " + _userName);
            }
        }
        private int UserInfoGetCount(string username)
        {
            //return Convert.ToInt32(SearchValue("select count(id) from userinfo where username='" + username + "'"));
            return username == "admin" ? 1 : 0;
        }
    }
View Code
复制代码

      f. 通过Javascript 和 jQuery 调用 Web API

复制代码
 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Product App</title>
</head>
<body>
    <div>
        <h2>All Products</h2>
        <ul id="products" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product" />
    </div>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
    var uri = 'api/Products';
    $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
              // Add a list item for the product.
              $('<li>', { 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>
index.html内容
复制代码

 

4. webapi部署

    a. 打包发布

     b. 部署到IIS(打开iis,选中网站,右键 添加网站)一般用localhost不要改

 

 

 

posted @   apple-hu  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示