C# · 12月 24, 2021

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;