如何在 Asp net Core 上最小化 HttpContext [英] How to moq HttpContext on Asp net Core

查看:26
本文介绍了如何在 Asp net Core 上最小化 HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 asp .net 核心项目,实际上在我们使用 session 的每个操作中,我的问题是如果我没有 sessionRepository 如何测试它.控制器测试崩溃,因为控制器中的会话为空.我尝试 Moq IHttpContextAcessor 并且它也不起作用.

I have an asp .net core project, and practically in each action we use session, my question is how to test it if I don't have sessionRepository. Controller tests crush because session in controller is null. I try to Moq IHttpContextAcessor and it also doesn't work.

我试试这个:

HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));

但 HttpContext 不包含 Current 的定义.(使用 Microsoft.AspNetCore.Http;)

but HttpContext doesn't contain the definition for Current. (using Microsoft.AspNetCore.Http;)

有没有办法对使用 HttpContext 和会话的控制器进行最小起订量或测试?

Is there any way to moq or test controllers that use HttpContext and sessions?

推荐答案

您可以使用 ControllerContext 将上下文设置为 DefaultHttpContext 您可以根据需要进行修改.

You can use ControllerContext to set the context to be DefaultHttpContext which you can modify to your needs.

var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext()};
var tested = new MyCtrl();
tested.ControllerContext = ctx;

这篇关于如何在 Asp net Core 上最小化 HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆