Disable outputcache programmically before it happens that isn't an exception - asp.net

Is there a way to disable the outputcache here programmatically if something happens that is not an exception?
[OutputCache(CacheProfile = "StatisticSheets")]
public virtual ActionResult GameStatistics(int? eventId, int? divisionId, string ids)
{
If(true) {
// Don't Cache This Page
}
return View();
}

This is how i have done:
create a derive class from outputcache:
public class MyOutputCache : OutputCacheAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// checking route data for special condition
if(!filterContext.RouteData.Values.TryGetValue("abortcaching",out object _))
{
base.OnResultExecuting(filterContext);
}
}
}
then in controller:
[MyOutputCache(Duration = 60, VaryByParam = "none")]
public ActionResult Index()
{
ViewBag.Title = "Home Page " + DateTime.Now.Minute.ToString();
// it can be your condition
if (DateTime.Now.Minute %2 == 0)
{
RouteData.Values.Add("abortcaching", "true");
}
return View();
}
hope it helps.

If you need global to disable then read the below details, at the end also I shared with action method implementation code.
First, we want to capture whether or not the app is in debugging mode when it is launched. We'll store that in a global variable to keep things speedy.
public static class GlobalVariables
{
public static bool IsDebuggingEnabled = false;
}
Then in the Global.asax code's Application_Start method, write to the global property.
protected void Application_Start()
{
SetGlobalVariables();
}
private void SetGlobalVariables()
{
CompilationSection configSection = (CompilationSection)ConfigurationManager
.GetSection("system.web/compilation");
if (configSection?.Debug == true)
{
GlobalVariables.IsDebuggingEnabled = true;
}
}
Now we will create our own class to use for caching, which will inherit from OutputCacheAttribute.
public class DynamicOutputCacheAttribute : OutputCacheAttribute
{
public DynamicOutputCacheAttribute()
{
if (GlobalVariables.IsDebuggingEnabled)
{
this.VaryByParam = "*";
this.Duration = 0;
this.NoStore = true;
}
}
}
Now when you decorate your controller endpoints for caching, simply use your new attribute instead of [OutputCache].
// you can use CacheProfiles or manually pass in the arguments, it doesn't matter.
// either way, no caching will take place if the app was launched with debugging
[DynamicOutputCache(CacheProfile = "Month")]
public ViewResult contact()
{
return View();
}
With Action Method
-> For .net Framework: [OutputCache(NoStore = true, Duration = 0)]
-> For .net Core: [ResponseCache(NoStore = true, Duration = 0)]
You can use the particular action method above way

Related

Mixing Custom and Default Model Binding

I need to run some code to further databind some model after the default model binding is done. I don't want to completely replace the existing model binding.
This question explains how this is done in pre-CORE ASP.NET:
ASP.NET MVC - Mixing Custom and Default Model Binding
However that approach doesn't seem to work in ASP.NET Core because there is no DefaultModelBinder class any more.
What alternative can be used in ASP.NET Core?
You can leverage the ComplexTypeModelBinder to do the actual work, then inject your own logic after it is done.
For example (assuming your custom type is MyCustomType):
public class MyCustomType
{
public string Foo { get; set; }
}
public class MyCustomTypeModelBinder : IModelBinder
{
private readonly IDictionary<ModelMetadata, IModelBinder> _propertyBinders;
public MyCustomTypeModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders)
{
this._propertyBinders = propertyBinders;
}
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
var complexTypeModelBinder = new ComplexTypeModelBinder(this._propertyBinders);
// call complexTypeModelBinder
await complexTypeModelBinder.BindModelAsync(bindingContext);
var modelBound = bindingContext.Model as MyCustomType;
// do your own magic here
modelBound.Foo = "custominjected";
}
}
public class MyCustomTypeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(MyCustomType))
{
var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
for (var i = 0; i < context.Metadata.Properties.Count; i++)
{
var property = context.Metadata.Properties[i];
propertyBinders.Add(property, context.CreateBinder(property));
}
return new MyCustomTypeModelBinder(propertyBinders);
}
return null;
}
}
Then register it:
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new MyCustomTypeModelBinderProvider());
});

MVC basecontroller doesn't return to controller after Initializing ASP.NET

First off all i'm fairly new to C# and ASP.NET (mainly program java).
I've got a BaseController where i want to fill a viewbag for all my other controllers to use. I also set some session data and create some cookies. This is the basecontroller:
public abstract partial class BaseController : Controller
{
// GET: Base
protected override void Initialize(RequestContext requestContext)
{
try
{
//Checks if the user is logged in
if (requestContext.HttpContext.Session["customer"] != null)
{
ViewBag.Customer = requestContext.HttpContext.Session["customer"];
ViewBag.Points = requestContext.HttpContext.Session["points"];
ViewBag.CardNumber = requestContext.HttpContext.Session["cardNumber"];
}
//Gets the products to be displayed
var products = ProductList.Instance.AsQueryable();
ViewBag.Products = products;
//Checks to see if the user has a cart added to his requestContext.HttpContext.Session
if (requestContext.HttpContext.Session["cart"] == null)
{
requestContext.HttpContext.Session["cart"] = new Cart();
}
Cart cart = (Cart)requestContext.HttpContext.Session["cart"];
ViewBag.CartCount = cart.Count();
if (requestContext.HttpContext.Session["ticketID"] == null)
{
requestContext.HttpContext.Session["ticketID"] = Guid.NewGuid();
}
//Adds a cookie to the user with his selected theme
HttpCookie cookieUserTheme = requestContext.HttpContext.Request.Cookies["cookieUserTheme"];
if (cookieUserTheme != null)
{
requestContext.HttpContext.Session["UserPref"] = UserModel.GetThemeByName(cookieUserTheme.Value);
}
else
{
requestContext.HttpContext.Session["UserPref"] = UserModel.GetThemeByName("5");
var cookie = new HttpCookie("cookieUserTheme", ((UserPref)requestContext.HttpContext.Session["UserPref"]).ID);
cookie.Expires = DateTime.Now.AddDays(90);
requestContext.HttpContext.Response.Cookies.Add(cookie);
}
ViewBag.UserPref = requestContext.HttpContext.Session["UserPref"];
}
catch (Exception ex)
{
throw ex;
}
}
}
}
And this is the controller.
public class AdminController : BaseController
{
// GET: Admin
public ActionResult Index()
{
ViewBag.Themes = SiteMethods.GetAllThemes();
return View();
}
But when this is done running it just goes to the following ASP.NET page
What am i doing wrong? Do i need a redirect from my basecontroller?
If you're overriding Controller.Initialize() with your own initialization logic, you need to call base.Initialize(requestContext) to continue with the regular initialization process:
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
// rest of your code
// ...
}
Otherwise, this.ControllerContext (that is being used internally by several properties), would be null.
See Source

Dependency injection inside a FilterAttribute in ASP.NET MVC 6

I'm struggling with ASP.NET MVC 6 (beta 4 release) trying to inject a service within a controller filter attribute of type AuthorizationFilterAttribute.
This is the service (it has another service injected)
public class UsersTableRepository
{
private readonly NeurosgarContext _dbContext;
public UsersTableRepository(NeurosgarContext DbContext)
{
_dbContext = DbContext;
}
public ICollection<User> AllUsers
{
get
{
return _dbContext.Users.ToList();
}
}
//other stuff...
}
This is the ConfigureServices method in Startup class for services enabling
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddSingleton<NeurosgarContext>(a => NeurosgarContextFactory.GetContext());
services.AddSingleton<UifTableRepository<Nazione>>();
services.AddSingleton<UsersTableRepository>();
}
A simple "dummy" controller with two filters defined on it. You can notice that I already done DI inside this controller by decorating the property with [FromServices]and it works.
[Route("[controller]")]
[BasicAuthenticationFilter(Order = 0)]
[BasicAuthorizationFilter("Admin", Order = 1)]
public class DummyController : Controller
{
[FromServices]
public UsersTableRepository UsersRepository { get; set; }
// GET: /<controller>/
[Route("[action]")]
public IActionResult Index()
{
return View();
}
}
Doing the same DI within BasicAuthenticationFilterdoes not work and at runtime UserRepository property is a null reference.
public class BasicAuthenticationFilterAttribute : AuthorizationFilterAttribute
{
[FromServices]
public UsersTableRepository UsersRepository { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!Authenticate(filterContext.HttpContext))
{
// 401 Response
var result = new HttpUnauthorizedResult();
// Add the header for Basic authentication require
filterContext.HttpContext.Response.Headers.Append("WWW-Authenticate", "Basic");
filterContext.Result = result;
//if (!HasAllowAnonymous(context))
//{
// base.Fail(context);
//}
}
}
// ...
}
Any idea about how solve this?
Refrain from injecting dependencies into your attributes as explained here. Make your attributes passive, or make your attribute a humble object as described here.
var dependencyScope = context.HttpContext.RequestServices;
var usersRepository = dependencyScope.GetService(typeof(UsersTableRepository)) as UsersTableRepository;
// usersRepository is now ready to be used
So your BasicAuthenticationFilter will look like this:
public class BasicAuthenticationFilterAttribute : AuthorizationFilterAttribute
{
public UsersTableRepository UsersRepository { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
var dependencyScope = context.HttpContext.RequestServices;
UsersRepository = dependencyScope.GetService(typeof(UsersTableRepository)) as UsersTableRepository;
if (!Authenticate(filterContext.HttpContext))
{
// 401 Response
var result = new HttpUnauthorizedResult();
// Add the header for Basic authentication require
filterContext.HttpContext.Response.Headers.Append("WWW-Authenticate", "Basic");
filterContext.Result = result;
//if (!HasAllowAnonymous(context))
//{
// base.Fail(context);
//}
}
}
// ...
}

How do you abstract page session properties?

I was following this example
example code:
public class Global : HttpApplication
{
private Poster _posterDetails;
private Posting _postingDetails;
private Property _propertyDetails;
protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Session == null) return;
_posterDetails = HttpContext.Current.Session["Poster"] as Poster;
_postingDetails = HttpContext.Current.Session["Posting"] as Posting;
_propertyDetails = HttpContext.Current.Session["Property"] as Property;
}
}
these session variables are littered throughout the app and I need to abstract the retrieval of them. Say, later I get them from a db instead of the current session.
Session is baked into the Page or Context. How do I inject that dependency into the concrete implementation of a possible current property getter.
Create an abstraction around HttpContext:
public interface IHttpContextFactory
{
HttpContextBase Create();
}
public class HttpContextFactory
: IHttpContextFactory
{
public HttpContextBase Create()
{
return new HttpContextWrapper(HttpContext.Current);
}
}
Then inject it into a specialized service for these settings.
public interface ISettings
{
T GetValue<T>(string key);
void SetValue<T>(string key, T value);
}
public class ContextSettings
: ISettings
{
private readonly IHttpContextFactory httpContextFactory;
private HttpContextBase context;
public RequestCache(
IHttpContextFactory httpContextFactory
)
{
if (httpContextFactory == null)
throw new ArgumentNullException("httpContextFactory");
this.httpContextFactory = httpContextFactory;
}
protected HttpContextBase Context
{
get
{
if (this.context == null)
{
this.context = this.httpContextFactory.Create();
}
return context;
}
}
public virtual T GetValue<T>(string key)
{
if (this.Context.Session.Contains(key))
{
return (T)this.Context.Session[key];
}
return default(T);
}
public virtual void SetValue<T>(string key, T value)
{
this.Context.Session[key] = value;
}
}
It will later be possible to replace the service with another storage mechanism by implementing ISettings and providing different constructor dependencies. Note that changing the constructor signature does not require a different interface.
That said, you should provide another service (or perhaps more than one) that takes ISettings as a dependency so you can make explicit properties. You should aim to provide focused sets of related properties for specific purposes. Your application also shouldn't have to know the type of property in order to retrieve its value - it should just call a property that hides those details.
public class SomeSettingsService: ISomeSettingsService
{
private readonly ISettings settings;
public SomeSettingsService(ISettings settings)
{
if (settings == null)
throw new ArgumentNullException("settings");
this.settings = settings;
}
public Poster Poster
{
get { return this.settings.GetValue<Poster>("Poster"); }
set { this.settings.SetValue<Poster>("Poster", value); }
}
public Posting Posting
{
get { return this.settings.GetValue<Posting>("Posting"); }
set { this.settings.SetValue<Posting>("Posting", value); }
}
public Property Property
{
get { return this.settings.GetValue<Property>("Property"); }
set { this.settings.SetValue<Property>("Property", value); }
}
}
Not sure if this is what you are asking... What I often do is create a service:
public interface ISessionService
{
object Get(string key);
void Save(string key, object value);
}
And then I implement this, which calls HttpContext.Current.Session[key] and returns the value. It shouldn't be hard to create a Get<T>(string key) to return an object either. Break all of your dependencies to use this (which is the hard part).
There is no seamless way to break the dependency... it has to be through a manual change.

How to return a view for HttpNotFound() in ASP.Net MVC 3?

Is there a way to return the same view every time a HttpNotFoundResult is returned from a controller? How do you specify this view? I'm guessing configuring a 404 page in the web.config might work, but I wanted to know if there was a better way to handle this result.
Edit / Follow up:
I ended up using the solution found in the second answer to this question with some slight tweaks for ASP.Net MVC 3 to handle my 404s: How can I properly handle 404s in ASP.Net MVC?
HttpNotFoundResult doesn't render a view. It simply sets the status code to 404 and returns an empty result which is useful for things like AJAX but if you want a custom 404 error page you could throw new HttpException(404, "Not found") which will automatically render the configured view in web.config:
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="/Http404.html" />
</customErrors>
This solution combines IResultFilter and IExceptionFilter to catch either thrown HttpException or returned HttpStatusCodeResult from within an action.
public class CustomViewForHttpStatusResultFilter: IResultFilter, IExceptionFilter
{
string viewName;
int statusCode;
public CustomViewForHttpStatusResultFilter(HttpStatusCodeResult prototype, string viewName)
: this(prototype.StatusCode, viewName) {
}
public CustomViewForHttpStatusResultFilter(int statusCode, string viewName) {
this.viewName = viewName;
this.statusCode = statusCode;
}
public void OnResultExecuted(ResultExecutedContext filterContext) {
HttpStatusCodeResult httpStatusCodeResult = filterContext.Result as HttpStatusCodeResult;
if (httpStatusCodeResult != null && httpStatusCodeResult.StatusCode == statusCode) {
ExecuteCustomViewResult(filterContext.Controller.ControllerContext);
}
}
public void OnResultExecuting(ResultExecutingContext filterContext) {
}
public void OnException(ExceptionContext filterContext) {
HttpException httpException = filterContext.Exception as HttpException;
if (httpException != null && httpException.GetHttpCode() == statusCode) {
ExecuteCustomViewResult(filterContext.Controller.ControllerContext);
// This causes ELMAH not to log exceptions, so commented out
//filterContext.ExceptionHandled = true;
}
}
void ExecuteCustomViewResult(ControllerContext controllerContext) {
ViewResult viewResult = new ViewResult();
viewResult.ViewName = viewName;
viewResult.ViewData = controllerContext.Controller.ViewData;
viewResult.TempData = controllerContext.Controller.TempData;
viewResult.ExecuteResult(controllerContext);
controllerContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
You can register this filter so, specifying either the http status code of the HttpException or the concrete HttpStatusCodeResult for which you want to display the custom view.
GlobalFilters.Filters.Add(new CustomViewForHttpStatusResultFilter(new HttpNotFoundResult(), "Error404"));
// alternate syntax
GlobalFilters.Filters.Add(new CustomViewForHttpStatusResultFilter(404, "Error404"));
It handles exceptions and HttpStatusCodeResult thrown or returned within an action. It won't handle errors that occur before MVC selects a suitable action and controller like this common problems:
Unknown routes
Unknown controllers
Unknown actions
For handling these types of NotFound errors, combine this solution with other solutions to be found in stackoverflow.
Useful info from #Darin Dimitrov that HttpNotFoundResult is actually returning empty result.
After some study. The workaround for MVC 3 here is to derive all HttpNotFoundResult, HttpUnauthorizedResult, HttpStatusCodeResult classes and implement new (overriding it) HttpNotFound() method in BaseController.
It is best practise to use base Controller so you have 'control' over all derived Controllers.
I create new HttpStatusCodeResult class, not to derive from ActionResult but from ViewResult to render the view or any View you want by specifying the ViewName property. I follow the original HttpStatusCodeResult to set the HttpContext.Response.StatusCode and HttpContext.Response.StatusDescription but then base.ExecuteResult(context) will render the suitable view because again I derive from ViewResult. Simple enough is it? Hope this will be implemented in the MVC core.
See my BaseController bellow:
using System.Web;
using System.Web.Mvc;
namespace YourNamespace.Controllers
{
public class BaseController : Controller
{
public BaseController()
{
ViewBag.MetaDescription = Settings.metaDescription;
ViewBag.MetaKeywords = Settings.metaKeywords;
}
protected new HttpNotFoundResult HttpNotFound(string statusDescription = null)
{
return new HttpNotFoundResult(statusDescription);
}
protected HttpUnauthorizedResult HttpUnauthorized(string statusDescription = null)
{
return new HttpUnauthorizedResult(statusDescription);
}
protected class HttpNotFoundResult : HttpStatusCodeResult
{
public HttpNotFoundResult() : this(null) { }
public HttpNotFoundResult(string statusDescription) : base(404, statusDescription) { }
}
protected class HttpUnauthorizedResult : HttpStatusCodeResult
{
public HttpUnauthorizedResult(string statusDescription) : base(401, statusDescription) { }
}
protected class HttpStatusCodeResult : ViewResult
{
public int StatusCode { get; private set; }
public string StatusDescription { get; private set; }
public HttpStatusCodeResult(int statusCode) : this(statusCode, null) { }
public HttpStatusCodeResult(int statusCode, string statusDescription)
{
this.StatusCode = statusCode;
this.StatusDescription = statusDescription;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.HttpContext.Response.StatusCode = this.StatusCode;
if (this.StatusDescription != null)
{
context.HttpContext.Response.StatusDescription = this.StatusDescription;
}
// 1. Uncomment this to use the existing Error.ascx / Error.cshtml to view as an error or
// 2. Uncomment this and change to any custom view and set the name here or simply
// 3. (Recommended) Let it commented and the ViewName will be the current controller view action and on your view (or layout view even better) show the #ViewBag.Message to produce an inline message that tell the Not Found or Unauthorized
//this.ViewName = "Error";
this.ViewBag.Message = context.HttpContext.Response.StatusDescription;
base.ExecuteResult(context);
}
}
}
}
To use in your action like this:
public ActionResult Index()
{
// Some processing
if (...)
return HttpNotFound();
// Other processing
}
And in _Layout.cshtml (like master page)
<div class="content">
#if (ViewBag.Message != null)
{
<div class="inlineMsg"><p>#ViewBag.Message</p></div>
}
#RenderBody()
</div>
Additionally you can use a custom view like Error.shtml or create new NotFound.cshtml like I commented in the code and you may define a view model for the status description and other explanations.
protected override void HandleUnknownAction(string actionName)
{
ViewBag.actionName = actionName;
View("Unknown").ExecuteResult(this.ControllerContext);
}
Here is true answer which allows fully customize of error page in single place.
No need to modify web.confiog or create sophisticated classes and code.
Works also in MVC 5.
Add this code to controller:
if (bad) {
Response.Clear();
Response.TrySkipIisCustomErrors = true;
Response.Write(product + I(" Toodet pole"));
Response.StatusCode = (int)HttpStatusCode.NotFound;
//Response.ContentType = "text/html; charset=utf-8";
Response.End();
return null;
}
Based on http://www.eidias.com/blog/2014/7/2/mvc-custom-error-pages
Please follow this if you want httpnotfound Error in your controller
public ActionResult Contact()
{
return HttpNotFound();
}

Resources