我正在使用单例模式我自己的ApplicationContext类.我想将它的实例存储在HttpContext.Items中,因为它可以在请求的所有部分中访问.我一直在阅读将HttpContext与ASP.NET MVC一起使用,其中一个主要问题是它引入了测试复杂性.我已经尝试过对HttpContext.Items的可测试性进行研究,但我能找到的就是Session上的内容.我发现的唯一一件事是在Wrox上的Professional ASP.NET 3.5 MVC书中的一个示例章节(这里是pdf链接).在第15页,它说:
你不能使用的东西:HttpContext.Items
在本节的上面,我们来了,告诉你我们骗了你:ASP.NET MVC和ASP.NET Web Forms之间没有共享HttpContext.因此,您无法使用HttpContext.Items集合来存储和检索数据位.
这是因为一旦你重定向到一个Controller,你的HttpHandler就变成了System.Web.Mvc.MvcHandler,它是使用HttpContextWrapper创建的,它将有自己的HttpContext.Current定义.不幸的是,在此握手期间,HttpContext.Items之类的东西不会被传输.
这归结为HttpContext类型,尽管看起来和听起来非常相似,但是不一样,并且你不能以这种方式传递数据.
现在,我已经尝试过对此进行测试,据我所知,如果使用RedirectToAction重定向到另一个控制器,HttpContext.Items仍会保留.我正在使用默认的ASP.NET MVC项目来测试它.我所做的是,将此方法添加到Global.asax.cs:
protected void Application_BeginRequest()
{
Context.Items["Test"] = "Hello World";
}
Run Code Online (Sandbox Code Playgroud)
在HomeController.cs中,我将Index方法更改为:
public ActionResult Index()
{
return RedirectToAction("About");
}
Run Code Online (Sandbox Code Playgroud)
并将About方法更改为:
public ActionResult About()
{
Response.Write(Convert.ToString(HttpContext.Items["Test"]));
return View();
}
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序时,页面正确地重定向到/ Home/About和Response.Writes在global.asax.cs中设置正确的"Hello World"字符串.
所以,在我看来,当他们说"像HttpContext.Items这样的东西没有转移"时,我或者不理解这本书是什么意思,或者它确实转移了这些东西,并且可以使用HttpContext.Items.
如果你们建议我避免使用HttpContext.Items,是否有另一种方法可以在每个请求的基础上跨请求存储对象?
我正在开发一个需要获取HTTP Post请求并将其读入字节数组以进行进一步处理的网页.我有点坚持如何做到这一点,我很难理解什么是最好的方法.到目前为止,这是我的代码:
public override void ProcessRequest(HttpContext curContext)
{
if (curContext != null)
{
int totalBytes = curContext.Request.TotalBytes;
string encoding = curContext.Request.ContentEncoding.ToString();
int reqLength = curContext.Request.ContentLength;
long inputLength = curContext.Request.InputStream.Length;
Stream str = curContext.Request.InputStream;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在检查请求的长度及其总字节数等于128.现在我只需要使用Stream对象将其转换为byte []格式吗?我正朝着正确的方向前进吗?不知道如何继续.任何建议都会很棒.我需要将整个HTTP请求放入byte []字段.
谢谢!
我正在使用异步操作并使用像这样的HttpContext.Current.User
public class UserService : IUserService
{
public ILocPrincipal Current
{
get { return HttpContext.Current.User as ILocPrincipal; }
}
}
public class ChannelService : IDisposable
{
// In the service layer
public ChannelService()
: this(new Entities.LocDbContext(), new UserService())
{
}
public ChannelService(Entities.LocDbContext locDbContext, IUserService userService)
{
this.LocDbContext = locDbContext;
this.UserService = userService;
}
public async Task<ViewModels.DisplayChannel> FindOrDefaultAsync(long id)
{
var currentMemberId = this.UserService.Current.Id;
// do some async EF request …
}
}
// In the controller
[Authorize]
[RoutePrefix("channel")]
public class …Run Code Online (Sandbox Code Playgroud) 上下文:.Net 3.5,C#
我想在我的控制台应用程序中使用缓存机制.
我想使用System.Web.Caching.Cache(而这是最后的决定,我不能使用其他缓存框架,不要问为什么),而不是重新发明轮子.
但是,它看起来System.Web.Caching.Cache应该只在有效的HTTP上下文中运行.我非常简单的代码片段如下所示:
using System;
using System.Web.Caching;
using System.Web;
Cache c = new Cache();
try
{
c.Insert("a", 123);
}
catch (Exception ex)
{
Console.WriteLine("cannot insert to cache, exception:");
Console.WriteLine(ex);
}
Run Code Online (Sandbox Code Playgroud)
结果是:
cannot insert to cache, exception: System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Caching.Cache.Insert(String key, Object value) at MyClass.RunSnippet()
显然,我在这里做错了.有任何想法吗?
更新:+1到大多数答案,通过静态方法获取缓存是正确的用法,即HttpRuntime.Cache和HttpContext.Current.Cache.谢谢你们!
我刚开始在ASP.NET AJAX中使用WCF服务.我从Javascript实例化我的WCF服务,然后将字符串变量作为参数传递给我的WCF服务方法(带有OperationContract签名).然后我返回一个.NET对象(使用DataContract定义),该对象绑定到我的自定义Javascript类.我根据登录到我的网络会话的用户进行身份验证时遇到问题.但是,WCF Web服务是一个完全不同的服务,没有HttpContext.Current对象的上下文.访问该对象的最安全的方法是什么?
这可能不是使用控制器的正确方法,但我确实注意到了这个问题并且没有找到解决方法.
public JsonResult SomeControllerAction() {
//The current method has the HttpContext just fine
bool currentIsNotNull = (this.HttpContext == null); //which is false
//creating a new instance of another controller
SomeOtherController controller = new SomeOtherController();
bool isNull = (controller.HttpContext == null); // which is true
//The actual HttpContext is fine in both
bool notNull = (System.Web.HttpContext.Current == null); // which is false
}
Run Code Online (Sandbox Code Playgroud)
我注意到Controller上的HttpContext不是你在System.Web.HttpContext.Current中找到的"实际"HttpContext.
有没有办法在Controller上手动填充HttpContextBase?或者更好的方法来创建Controller的实例?
嗨,我使用自定义MembershipProvider.
我想知道应用程序场景中的当前用户名,但是当我尝试访问HttpContext.Current.User.Identity.Name时,它总是返回string.Empty.
if (Membership.ValidateUser(tbUsername.Text, tbPassword.Text))
{
FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
bool x = User.Identity.IsAuthenticated; //true
string y = User.Identity.Name; //""
FormsAuthentication.RedirectFromLoginPage(tbUsername.Text, cbRememberMe.Checked);
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
我问了一个相关的问题但是搞砸了标题,没有人会理解它.由于我现在能够更准确地提出这个问题,我决定在一个新问题中重新制定它并关闭旧问题.对不起.
所以我想要做的是将数据(我的自定义用户的昵称存储在数据库中)传递给LoginUserControl.此登录通过Html.RenderPartial()从主页面呈现,因此我真正需要做的是确保每次调用时都出现ViewData ["UserNickname"].但我不想在每个控制器的每个动作中填充ViewData ["UserNickname"],所以我决定使用这种方法并创建一个抽象的基本控制器,它将为我完成工作,如下所示:
public abstract class ApplicationController : Controller
{
private IUserRepository _repUser;
public ApplicationController()
{
_repUser = RepositoryFactory.getUserRepository();
var loggedInUser = _repUser.FindById(User.Identity.Name); //Problem!
ViewData["LoggedInUser"] = loggedInUser;
}
}
Run Code Online (Sandbox Code Playgroud)
这样,无论我的推导控制器做什么,用户信息都已经存在.
到现在为止还挺好.现在出现问题:
我无法调用User.Identity.Name,因为User它已经为空.在我的所有派生控制器中都不是这种情况,因此这是抽象基本控制器特有的.
我在代码中的另一个地方通过FormsAuthentication设置User.Identity.Name,但我认为这不是问题 - afaik User.Identity.Name可以为null,但不是User本身.
在我看来HttpContext不可用(因为也是null ;-)而且我在这里错过了一个简单而重要的观点.任何人都可以给我一些提示吗?我真的很感激.
我正在开发一个项目,我有一个需要使用的C#类库System.web.HttpContext.我之前在另一个项目中做过这个没有问题,但现在它没有工作.我不确定我错过了什么,他们都瞄准.net 3.5并且我添加了引用System.web并添加了指令using System.web.
但是,当我尝试并且什么HttpContext都不做时.我尝试使用完整路径,System.web.HttpContext但唯一出现的是与ASP相关的3个项目.
以下是工作项目智能感知和非工作智能感知的截图
下面是工作截图

以下是非工作截图

感谢您的任何帮助,您可以提供
我在一个单独的线程上做一些异步工作:
ThreadPool.QueueUserWorkItem()
Run Code Online (Sandbox Code Playgroud)
在这个单独的线程中,我需要调用HttpContext.Current以便我可以访问:
HttpContext.Current.Cache
HttpContext.Current.Server
HttpContext.Current.Request
Run Code Online (Sandbox Code Playgroud)
但是,HttpContext.Current当我创建这个单独的线程时,它为null.
如何创建新线程以使其HttpContext.Current不为空?或者是否有另一种方法可以访问Cache,Server和Request对象?
httpcontext ×10
asp.net-mvc ×4
c# ×4
asp.net ×3
system.web ×2
.net ×1
async-await ×1
caching ×1
controller ×1
iidentity ×1
service ×1
wcf ×1