简体   繁体   English

如何在“天蓝色函数”上模拟 HttpRequest

[英]How do I mock the HttpRequest on an "azure function"

I have a function with an Http trigger我有一个 function 和一个 Http 触发器

public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function,"post", Route = null)] HttpRequest req)

I want to mock the req.我想模拟请求。 I have manage to do so just fine like this我已经设法像这样做到了

private static Mock<HttpRequest> CreateMockRequest(object body)
{            
    using var memoryStream= new MemoryStream();
    using var writer = new StreamWriter(memoryStream);
 
    var json = JsonConvert.SerializeObject(body);
 
    writer .Write(json);
    writer .Flush();
 
    memoryStream.Position = 0;
 
    var mockRequest = new Mock<HttpRequest>();
    mockRequest.Setup(x => x.Body).Returns(memoryStream);
    mockRequest.Setup(x => x.ContentType).Returns("application/json");

    return mockRequest;
}

body, in the above code is just some json. I am then using this code to deserialize this the json stuffed in the body of the mockRequest正文,在上面的代码中只是一些 json。然后我使用这段代码反序列化这个 json 填充在 mockRequest 的正文中

public static async Task<HttpResponseBody<T>> GetBodyAsync<T>(this HttpRequest req)
    using var stream = new StreamReader(req.Body);
    var bodyString = await stream.ReadToEndAsync();
...
}

The bodyString is not valid json here because there seems to be escaping of the quotes in the json eg Original Json = {"x": "somexvalue"} the value coming back = {\"x\": \"somexvalue\" bodyString 在这里无效 json 因为似乎有 json 中引号的 escaping eg Original Json = {"x": "somexvalue"} the value coming back = {\"x\": \"somexvalue\"

Before you say that this is just visual studio debug inspector, it is not.在你说这只是 visual studio 调试检查器之前,它不是。 I have checked.我检查过。 It seems the StreamWriter is doing this or the StreamReader is.似乎StreamWriter正在这样做,或者StreamReader正在这样做。

The obvious solution was to just strip the \ out of the resulting json but this feels so wrong and work arroundy.显而易见的解决方案是将 \ 从生成的 json 中去掉,但这感觉很不对,而且工作范围很广。 Is there a way to fix this without having to change my function.有没有办法解决这个问题而不必更改我的 function.

So, the issue is with the StreamWritter .所以,问题出在StreamWritter上。 The way around it is just to not use the StreamWritter .解决方法就是不使用StreamWritter @ColinM was on the right line. @ColinM 在正确的线上。 This is the way to mock the body这是嘲讽身体的方法

    var json = JsonConvert.SerializeObject(body);

    var memoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

    var context = new DefaultHttpContext();
    var request = context.Request;
    request.Body = memoryStream;
    request.ContentType = "application/json";

    return request;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM