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

前端之家收集整理的这篇文章主要介绍了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;
原文链接:https://www.f2er.com/csharp/91962.html

猜你在找的C#相关文章