postman-pre-request-scripts使用

一、场景

postman-pre-request-scripts使用_第1张图片

二、定义模拟接口

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SaaS.Framework.DataTransfer;
using System.Threading.Tasks;

namespace SaaS.KDemo.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthPostmanController : ControllerBase
    {
        [AllowAnonymous]
        [HttpPost("getAuth")]
        [ProducesResponseType(typeof(OkResponse), StatusCodes.Status200OK)]
        public virtual async Task GetAuth([FromBody] InputPar inputPar)
        {
            return Ok(new SucceedResponse() { Data = new { SecreteKey = inputPar.ShopID + "_TQtNDQ0Mi00NThmL", SecreteToken = inputPar.ShopID + "_YTk2ZGUzOTQtNDQ0Mi00NThmLTgzMzktM2M3YmYyNGEwYjY0" } });
        }

        [AllowAnonymous]
        [HttpGet("getData")]
        [ProducesResponseType(typeof(OkResponse), StatusCodes.Status200OK)]
        public virtual async Task GetData(string  name,string secreteKey,string secreteToken)
        {
            return Ok(new SucceedResponse() { });
        }
    }

    public class InputPar
    {
        public int ShopID { get; set; }
    }
}
 
  

postman-pre-request-scripts使用_第2张图片

三、Postman

设置环境变量

postman-pre-request-scripts使用_第3张图片postman-pre-request-scripts使用_第4张图片

配置pre-request-scripts

var shopID= parseInt(pm.environment.get('ShopID')) ;
console.log(shopID)
 if(pm.request.method=="POST")
    {
        var raw=JSON.parse(pm.request.body.raw)
        console.log(raw)
        for(var key in raw)
        {
            console.log(key+':'+raw[key])
        }
    }
    else
    {
        var queryParam = pm.request.url.query.members
        console.log(queryParam)
        for (var item in queryParam) {
           
            if(queryParam[item].disabled)
            {
                continue;
            }
            console.log(queryParam[item].key+':'+queryParam[item])
        }
    }
var url="http://localhost:5901/api/AuthPostman/getAuth";

var getAuth = {
  url: url,
  header: {
        'content-type': 'application/json-patch+json'
    },
    method:"POST",
    body:{
        mode:"raw",
        raw:JSON.stringify({ shopID:shopID})
    }
};


pm.sendRequest(getAuth,function (err, response) {
    var res=response.json();
    console.log(res);
    if(res.succeed)
    {
        pm.collectionVariables.set("secreteKey", res.data.secreteKey);  
        pm.collectionVariables.set("secreteToken", res.data.secreteToken);  
    }
});

postman-pre-request-scripts使用_第5张图片

你可能感兴趣的:(工具,Jmeter,postman,测试工具)