pracuję z działaniami asynchronicznych i użyć HttpContext.Current.User jak tenPrawidłowe sposobem użycia HttpContext.Current.User z async czekają
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 ChannelController : BaseController
{
public ChannelController()
: this(new ChannelService()
{
}
public ChannelController(ChannelService channelService)
{
this.ChannelService = channelService;
}
// …
[HttpGet, Route("~/api/channels/{id}/messages")]
public async Task<ActionResult> GetMessages(long id)
{
var channel = await this.ChannelService
.FindOrDefaultAsync(id);
return PartialView("_Messages", channel);
}
// …
}
Mam kod niedawno refactored, wcześniej miałem dać użytkownik każdego połączenia z usługą. Teraz czytam ten artykuł http://trycatchfail.com/blog/post/Using-HttpContext-Safely-After-Async-in-ASPNET-MVC-Applications.aspx i nie jestem pewien, czy mój kod nadal działa. Czy ktoś ma lepsze podejście do obsługi tego? Nie chcę przekazywać użytkownikowi każdego żądania do usługi.
Jeśli chcesz wiedzieć, w którym środowisku wykonawczym działa twoja aplikacja ASP.NET, uderz w punkt przerwania i użyj właściwości statycznej: 'HttpRuntime.TargetFramework'. –