本文整理汇总了C#中System.Web.HttpContextWrapper类的典型用法代码示例。如果您正苦于以下问题:C# HttpContextWrapper类的具体用法?C# HttpContextWrapper怎么用?C# HttpContextWrapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpContextWrapper类属于System.Web命名空间,在下文中一共展示了HttpContextWrapper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ImportStylesheet
/// <summary>
/// Creates the proper CSS link reference within the target CSHTML page's head section
/// </summary>
/// <param name="virtualPath">The relative path of the image to be displayed, or its directory</param>
/// <returns>Link tag if the file is found.</returns>
public static ViewEngines.Razor.IHtmlString ImportStylesheet(string virtualPath)
{
ImageOptimizations.EnsureInitialized();
if (Path.HasExtension(virtualPath))
virtualPath = Path.GetDirectoryName(virtualPath);
var httpContext = new HttpContextWrapper(HttpContext.Current);
var cssFileName = ImageOptimizations.LinkCompatibleCssFile(httpContext.Request.Browser) ?? ImageOptimizations.LowCompatibilityCssFileName;
virtualPath = Path.Combine(virtualPath, cssFileName);
var physicalPath = HttpContext.Current.Server.MapPath(virtualPath);
if (File.Exists(physicalPath))
{
var htmlTag = new TagBuilder("link");
htmlTag.MergeAttribute("href", ResolveUrl(virtualPath));
htmlTag.MergeAttribute("rel", "stylesheet");
htmlTag.MergeAttribute("type", "text/css");
htmlTag.MergeAttribute("media", "all");
return new NonEncodedHtmlString(htmlTag.ToString(TagRenderMode.SelfClosing));
}
return null;
}
示例2: CreateController_WithRouteData_CreatesControllerInstance
public void CreateController_WithRouteData_CreatesControllerInstance()
{
var context = new HttpContextWrapper(new HttpContext(
new HttpRequest(null, "http://tempuri.org", null),
new HttpResponse(null)));
context.Items["CurrentResourcePackage"] = "test";
var layoutTemplateBuilder = new LayoutRenderer();
Controller dummyController = null;
SystemManager.RunWithHttpContext(context, () =>
{
var routeData = new RouteData();
routeData.Values.Add("controller", "dummy");
dummyController = layoutTemplateBuilder.CreateController(routeData);
});
Assert.IsNotNull(dummyController);
Assert.IsTrue(dummyController != null);
Assert.IsTrue(dummyController.ControllerContext != null);
Assert.IsTrue(dummyController.ControllerContext.RouteData != null);
Assert.IsTrue(dummyController.ControllerContext.RouteData.Values != null);
Assert.IsTrue(dummyController.ControllerContext.RouteData.Values.ContainsKey("controller"));
Assert.IsTrue(dummyController.ControllerContext.RouteData.Values["controller"] != null);
Assert.AreEqual<string>(dummyController.ControllerContext.RouteData.Values["controller"].ToString(), "dummy");
}
示例3: InitHelpers
public void InitHelpers()
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
var handler = httpContext.CurrentHandler as MvcHandler;
if (handler == null)
throw new InvalidOperationException("Unable to run template outside of ASP.NET MVC");
}
示例4: Application_Error
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Errors";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
//case 403:
// routeData.Values["action"] = "Http403";
// break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
IController errorsController = new ErrorsController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new RequestContext(wrapper, routeData);
errorsController.Execute(rc);
}
示例5: ProcessUserAuthorizationAsync
/// <summary>
/// The process user authorization.
/// </summary>
/// <param name="context">The HTTP context.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// The response message.
/// </returns>
public Task<AccessTokenResponse> ProcessUserAuthorizationAsync(HttpContextBase context = null, CancellationToken cancellationToken = default(CancellationToken)) {
if (context == null) {
context = new HttpContextWrapper(HttpContext.Current);
}
return this.webConsumer.ProcessUserAuthorizationAsync(context.Request.Url, cancellationToken: cancellationToken);
}
示例6: Application_Error
protected void Application_Error()
{
var httpContext = HttpContext.Current;
if (httpContext == null) return;
var context = new HttpContextWrapper(System.Web.HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(context);
var requestContext = new RequestContext(context, routeData);
/* when the request is ajax the system can automatically handle a mistake with a JSON response. then overwrites the default response */
if (requestContext.HttpContext.Request.IsAjaxRequest())
{
httpContext.Response.Clear();
var controllerName = requestContext.RouteData.GetRequiredString("controller");
var factory = ControllerBuilder.Current.GetControllerFactory();
var controller = factory.CreateController(requestContext, controllerName);
var controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);
var jsonResult = new JsonResult
{
Data = new {success = false, serverError = "500"},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
jsonResult.ExecuteResult(controllerContext);
httpContext.Response.End();
}
else
{
httpContext.Response.Redirect("~/Error");
}
}
示例7: ExecuteErrorPage
private void ExecuteErrorPage()
{
ErrorInfo errorInfo = new ErrorInfo(httpStatusCode, this.exception, HttpContext.Current.Request);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", this.config.ErrorControllerName);
routeData.Values.Add("action", this.config.ErrorActionName);
routeData.Values.Add("errorInfo", errorInfo);
HttpContextWrapper httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
RequestContext requestContext = new RequestContext(httpContextWrapper, routeData);
IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory();
IController errorController = controllerFactory.CreateController(requestContext, this.config.ErrorControllerName);
errorController.Execute(requestContext);
if (httpStatusCode > 0)
{
HttpContext.Current.Response.StatusCode = httpStatusCode;
HttpContext.Current.Response.ContentType = "text/html";
}
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
}
示例8: DoPasswordProtect
void DoPasswordProtect(HttpContextWrapper context)
{
var request = context.Request;
var response = context.Response;
//normally this would be some type of abstraction.
var username = ConfigurationManager.AppSettings["br-username"];
var password = ConfigurationManager.AppSettings["br-password"];
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
{
var data = String.Format("{0}:{1}", username, password);
var correctHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
string securityString = request.Headers["Authorization"];
if (securityString == null)
goto forceRedirect;
if (securityString != correctHeader)
goto forceRedirect;
goto end;
forceRedirect:
var host = request.Url.Host.ToLower();
response.AddHeader("WWW-Authenticate", String.Format(@"Basic realm=""{0}""", host));
response.StatusCode = 401;
response.End();
end:
;
}
}
示例9: For
public string For(string controller, string action, IDictionary<string, object> values)
{
var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));
return FullApplicationPath(httpContextWrapper.Request) + urlHelper.Action(action, controller, new RouteValueDictionary(values));
}
示例10: GetMatches
public IList<RouteData> GetMatches(string virtualPath)
{
HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
return GetMatches(virtualPath, "GET", context);
}
示例11: context_BeginRequest
void context_BeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var context = new HttpContextWrapper(application.Context);
DoPasswordProtect(context);
}
示例12: Application_Error
protected void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
if (ex != null)
{
var bhEx = ex as FlhException;
var context = new HttpContextWrapper(Context);
var errorCode = bhEx == null ? ErrorCode.ServerError : bhEx.ErrorCode;
var errorMsg = bhEx == null ? ex.ToString() : bhEx.Message;
if (context.Request.IsAjaxRequest())
{
Context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new Web.JsonResultEntry
{
Code = errorCode,
Message = errorMsg
}));
}
else
{
IController ec = new Controllers.ErrorController();
var routeData = new RouteData();
routeData.Values["action"] = "index";
routeData.Values["controller"] = "error";
routeData.DataTokens["code"] = errorCode;
routeData.DataTokens["msg"] = errorMsg;
ec.Execute(new RequestContext(context, routeData));
}
Server.ClearError();
}
}
示例13: RenderPartial
private static void RenderPartial(string partialName, object model, TextWriter output)
{
//get a wrapper for the legacy WebForm context
var httpCtx = new HttpContextWrapper(HttpContext.Current);
//create a mock route that points to the empty controller
var rt = new RouteData();
rt.Values.Add("controller", "WebFormController");
//create a controller context for the route and http context
var ctx = new ControllerContext(
new RequestContext(httpCtx, rt), new WebFormController());
//find the partial view using the view-engine
var view = ViewEngines.Engines.FindPartialView(ctx, partialName).View;
//create a view context and assign the model
var vctx = new ViewContext(ctx, view,
new ViewDataDictionary { Model = model },
new TempDataDictionary(),
httpCtx.Response.Output);
//render the partial view
view.Render(vctx, output);
}
示例14: Application_AuthenticateRequest
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var context = new HttpContextWrapper(HttpContext.Current);
if (!string.IsNullOrEmpty(AuthSettings.EnableAuth) &&
AuthSettings.EnableAuth.Equals(false.ToString(), StringComparison.OrdinalIgnoreCase))
{
context.User = new TryWebsitesPrincipal(new TryWebsitesIdentity("[email protected]", null, "Local"));
return;
}
if (!SecurityManager.TryAuthenticateSessionCookie(context))
{
if (SecurityManager.HasToken(context))
{
// This is a login redirect
SecurityManager.AuthenticateRequest(context);
return;
}
var route = RouteTable.Routes.GetRouteData(context);
// If the route is not registerd in the WebAPI RouteTable
// then it's not an API route, which means it's a resource (*.js, *.css, *.cshtml), not authenticated.
// If the route doesn't have authenticated value assume true
var isAuthenticated = route != null && (route.Values["authenticated"] == null || (bool)route.Values["authenticated"]);
if (isAuthenticated)
{
SecurityManager.AuthenticateRequest(context);
}
else if (context.IsBrowserRequest())
{
SecurityManager.HandleAnonymousUser(context);
}
}
}
示例15: Application_Error
protected void Application_Error(object sender, EventArgs e)
{
Exception lastError = Server.GetLastError();
Server.ClearError();
int statusCode = 0;
if (lastError.GetType() == typeof(HttpException))
{
statusCode = ((HttpException)lastError).GetHttpCode();
}
else
{
statusCode = 500;
}
HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("statusCode", statusCode);
routeData.Values.Add("exception", lastError);
IController controller = new ErrorController();
RequestContext requestContext = new RequestContext(contextWrapper, routeData);
controller.Execute(requestContext);
Response.End();
}