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

前端之家收集整理的这篇文章主要介绍了c# – 如何在FakeHttpContext中设置Request.Header以进行单元测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个FakeHttpContext我一直在尝试修改以包含一些标题用于测试目的
  1. public static HttpContext FakeHttpContext()
  2. {
  3. var httpRequest = new HttpRequest("","http://stackoverflow/","");
  4. var stringWriter = new StringWriter();
  5. var httpResponse = new HttpResponse(stringWriter);
  6. var httpContext = new HttpContext(httpRequest,httpResponse);
  7.  
  8. var sessionContainer = new HttpSessionStateContainer("id",new SessionStateItemCollection(),new HttpStaticObjectsCollection(),10,true,HttpCookieMode.AutoDetect,SessionStateMode.InProc,false);
  9.  
  10. httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
  11. BindingFlags.NonPublic | BindingFlags.Instance,null,CallingConventions.Standard,new[] { typeof(HttpSessionStateContainer) },null)
  12. .Invoke(new object[] { sessionContainer });
  13.  
  14. return httpContext;
  15. }

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

  1. httpRequest.Headers.Add("blah","1234");
  2. 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.
  1. var request = new HttpRequestMessage(HttpMethod.Get,"http://stackoverflow");
  2. request.Headers.Add("deviceId","1234");
  3. _myController.Request = request;

猜你在找的C#相关文章