首页 > 其他分享 >webapi测试例子

webapi测试例子

时间:2024-10-09 15:33:08浏览次数:1  
标签:webapi return string get 例子 result 测试 new public

 

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

 

标签:webapi,return,string,get,例子,result,测试,new,public
From: https://www.cnblogs.com/apple-hu/p/18454396

相关文章

  • 创建空webapi服务
     1.打开vs2019,选择创建新项目2.选择ASP.NETWeb应用程序(.NETFramework) 3.配置项目信息(名称,位置,框架)4.选择空模板(WebAPI复选框选中)5.这样里面就没有MVC的三层,因为前后端分离,webapi中只有两层。6.空的WebApi程序创建完成。 ......
  • 测试要不要转岗产品经理?
    星球有同学问了这样一个问题:在公司有机会转岗产品经理,目前是软件测试岗位,要不要转产品经理?老实说,测试转开发或者开发转测试的案例有很多,转岗后做的好的也不少,毕竟都是技术岗位,底层技术都是通用的。但测试转产品岗位确实比较少见,且成功的案例更是寥寥,因为这两者背后最大的差异是......
  • 智驾仿真测试实战之自动泊车HiL仿真测试
    1.引言 汽车进入智能化时代,自动泊车功能已成为标配。在研发测试阶段,实车测试面临测试场景覆盖度不足、效率低下和成本高昂等挑战。为解决这些问题,本文提出一种自动泊车HiL仿真测试系统方案,可大幅度提升测试效率及测试场景覆盖度、缩短测试周期、加速产品迭代升级。 2.自动泊......
  • 性能测试的类型有哪些
    目录1.基准测试2.负载测试3.压力测试4.峰值测试5.并发测试6.容积测试7.稳定性测试8.可扩展性测试9.配置测试性能测试是为测量或评估被测软件系统与性能效率相关的特性而实施的一类测试,它关注被测系统在不同负载下的各种性能效率。软件系统的性能效率相关特性的覆盖......
  • 高带宽示波器在信号测试分析中的优势和主要应用场景
    最近,普源精电推出了一款13GHz带宽的示波器DS81304,。有些小伙伴会好奇,为什么普源示波器的带宽会从5GHz跳到13GHz,为什么不是到10GHz或者15GHz呢?13GHz的示波器又能干些什么呢?下面讲为大家介绍,为什么DS81304设计为13GHz带宽,以及DS81304相比5GHz带宽的DS70504又能有什么特点。为......
  • 简单的c++实现消息发布/订阅机制例子(成员函数被其他类掉调用的例子)
    以下是一个简单的使用C++实现发布/订阅机制的示例代码。这个示例包含一个简单的事件系统,其中有发布者(Publisher)和订阅者(Subscriber)。以下代码需要C++11以上支持#include<iostream>#include<vector>#include<functional>//事件参数结构体,可以根据实际需求修改struc......
  • 【星闪开发连载】SLE_UUID_Server和SLE_UUID_Client程序测试
    引言前一篇博文介绍了SLE_UUID_Server和SLE_UUID_Client程序的基本结构,这篇介绍如何进行测试,从而实现两块星闪开发板之间的连接。服务器的构建在sdk根目录下(即src目录)打开集成终端台,执行python build.py-cws63-liteos-appmenuconfig命令,会出现选择弹窗。menuconfig这......
  • 软件测试与测试阶段
    软件测试概述    软件测试是使用人工或自动的手段来运行或测定某个软件系统的过程,其目的在于检验它是否满足规定的需求或弄清预期结果与实际结果之间的差别。    软件测试的目的就是确保软件的质量、确认软件以正确的方式做了用户所期望的事情,所以软件测试工......
  • kubekey 快速构建重构测试k8s 环境 allinone单机 or cluster 集群
    exportKKZONE=cncurl-sfLhttps://get-kk.kubesphere.io|VERSION=v3.0.13sh-生成配置k8s集群yml指定k8s版本及管理面板./kkcreateconfig--with-kubernetesv1.23.10--with-kubespherev3.4.1apiVersion:kubekey.kubesphere.io/v1alpha2kind:Clustermetada......
  • 课上测试:位运算(AI)
    2.使用位运算编写并调用下面函数,把当前时间(使用C库函数获得)设置到TIME中,给出代码,使用git记录过程。为了使用位运算将当前时间设置到一个自定义的TIME结构体或变量中(尽管通常我们不会直接用位运算来处理时间,因为时间通常是由多个独立的字段如小时、分钟、秒等组成的),我们可......