c# - 如何从 IOwinContext 获取 HttpRequestBase

标签 c# .net asp.net-web-api asp.net-web-api2 owin

我开始为我的 API 使用 Owin 自托管,现在我正在尝试修复一些测试,这些测试开始失败,因为 Owin 不支持 HttpContext.Current

现在我无法从 IOwinContext 获取 HttpRequestBase。这是我在 Owin 之前使用的旧代码:

public static HttpRequestBase GetRequestBase(this HttpRequestMessage request)
{
    return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request;
}

这是我基于 this answer 的尝试:

public static HttpRequestBase GetRequestBase(this HttpRequestMessage request)
{
    var context = request.GetOwinContext();

    HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName); // <---- Returns null

    return httpContext.Request;
}

问题是 httpContext 变量返回 null,我不知道出了什么问题。

有人知道如何使用 Owin 获取 HttpRequestBase 吗?

最佳答案

我猜您一定是在为您的 webApi 使用 System.web 托管,这就是您的测试运行的原因。现在,由于您已经开始使用托管 HttpContext 的 OwinSelf,图片中不再存在。这就是你变得空的原因。

这就是我们有扩展方法从 HttpContext/Requests 获取 OwinContext 但没有扩展方法从 OwinContext 获取 HttpContext 的原因。

很遗憾,您必须删除/更改上述自托管测试。

关于c# - 如何从 IOwinContext 获取 HttpRequestBase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30358113/

相关文章:

c# - .NET(非可视化)组件

c# - 如何让 Debug.WriteLine 在 Release 模式下写入输出窗口?

.net - 如何使用反射判断对象的类型是否为Nullable <T>?

wcf - 如何替换 Web Api 堆栈中的 DataContractResolver?

asp.net-web-api - 属性路由和继承

c# - 使用 C# 和 MySQL 的 Crystal 报表。正在设计但运行时总是登录失败

C# ASP.NET : Dynamically constructing an url query string

.net - 无法从 Swift 访问 HttpPost Web Api

c# - 以行值作为列的 SQL 查询的建议

C# 到 VB.Net 转换 - 具有初始化的类对象数组