c# – 如何在FakeHttpContext中设置Request.Header以进行单元测试

我有一个FakeHttpContext我一直在尝试修改以包含一些标题用于测试目的
public static HttpContext FakeHttpContext()
{
    var httpRequest = new HttpRequest("","http://stackoverflow/","");
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest,httpResponse);   

    var sessionContainer = new HttpSessionStateContainer("id",new SessionStateItemCollection(),new HttpStaticObjectsCollection(),10,true,HttpCookieMode.AutoDetect,SessionStateMode.InProc,false);

    httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                        BindingFlags.NonPublic | BindingFlags.Instance,null,CallingConventions.Standard,new[] { typeof(HttpSessionStateContainer) },null)
                                .Invoke(new object[] { sessionContainer });

    return httpContext;
 }

这可以在没有标题的情况下工作,但是当我在httpRequest和stringWriter行之间添加任何这些代码行时.

httpRequest.Headers.Add("blah","1234");
    httpRequest.Headers["blah"] = "1234";

它抛出

An exception of type ‘System.PlatformNotSupportedException’ occurred
in System.Web.dll but was not handled in user code

>为什么我得到那个例外?
>是否有可能的方法将标头添加到HttpContext进行测试
WebApi控制器?

解决方法

我刚刚发现,使用HttpRequestMessage类,您可以轻松添加标头以测试WebAPI控制器,而无需创建任何假的HttpContext.
var request = new HttpRequestMessage(HttpMethod.Get,"http://stackoverflow");
request.Headers.Add("deviceid","1234");
_myController.Request = request;

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...