Ho un'azione del controller che riceve un oggetto complesso come parametro, ho bisogno che OutputCache vari da una delle proprietà di questo oggetto complesso. È possibile? Come?OutputCache che varia a seconda della proprietà di un oggetto complesso
7
A
risposta
6
se si dispone di un modello come
public class person{
public string Name {get;set;}
public string location {get;set;}
}
e nel (fortemente tipizzato) visualizzare si dispone di un modulo
@model Person
@Html.BeginForm(){
@Html.TextBoxFor(x=>x.Name)
@Html.TextBoxFor(x=>x.location)
}
e si invia il modulo a un ActionResult
savePerson, con diversi firma come
public ActionResult savePerson(Person p){
// p.Name
// p.location
}
o
public ActionResult savePerson(string Name, string location){
}
quindi penso che se si annotare l'ActionResult come
[OutputCache(Duration=3600, VaryByParam="Name")]
public ActionResult savePerson(Person p)
{
//
return View();
}
lo farà per voi, o se si dispone di un modello complesso come
public class person{
public string Name {get;set;}
public Location loc {get;set;}
}
public class Location{
public string address
}
provare
[OutputCache(Duration=3600, VaryByParam="Person.Location.address")]
public ActionResult savePerson(Person p)
{
//
return View();
}
4
Ho avuto lo stesso requisito di cui sopra e ho trovato un approccio leggermente diverso
La classe
/// <summary>
/// This class is used to encapsulate search filters for monitor graphs
/// </summary>
public class DatacarMonitorSearchCriteriaModel
{
public int? SynergyCode { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
/// <summary>
/// Filter to apply
/// </summary>
public IEnumerable<int> Countries { get; set; }
public DatacarMonitorSearchCriteriaModel()
{
Countries = new List<int>();
}
}
OutputCacheComplexAttribute
/// <summary>
/// <para>
/// An instance of this class mimic the behaviour of OutputCacheAttribute but for complex objects.
/// </para>
/// <para>
/// It allows to cache the output of any action that takes complex objects
/// </para>
/// </summary>
public class OutputCacheComplexAttribute : OutputCacheAttribute
{
private readonly Type[] _types;
private string _cachedKey;
/// <summary>
/// Initializes a new instance of the <see cref="OutputCacheComplexAttribute"/> class.
/// </summary>
/// <param name="types">Types that this attribute will lookup for in QueryString/Form data and store values in cache.</param>
/// <exception cref="System.ArgumentOutOfRangeException">type;type cannot be null</exception>
public OutputCacheComplexAttribute(params Type[] types)
{
if (types == null)
{
throw new ArgumentOutOfRangeException("type", "type cannot be null");
}
_types = types;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
StringBuilder sbCachedKey = new StringBuilder();
if (filterContext.HttpContext.Request.Url != null)
{
string path = filterContext.HttpContext.Request.Url.PathAndQuery;
IDictionary<string, object> parameters = filterContext.ActionParameters;
//we need to compute a cache key which will be used to store the action output for later retrieval
//The cache key scheme is
// {url}:{key 1}:{value};[{key 2}:{value 2}[; ... {key n}:{value n}]];
// where :
// - url is the url of the action that will be executed
// - key n is the name of the n-th parameter
// - value n is the value of the n-th parameter as json string.
foreach (KeyValuePair<string, object> kv in parameters)
{
var kv1 = kv;
if (kv.Value != null && _types.AtLeastOnce(t => t.IsInstanceOfType(kv1.Value)))
{
sbCachedKey = sbCachedKey.AppendFormat("{0}:{1};",kv.Key,
JsonConvert.SerializeObject(kv.Value, Formatting.None, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
}
}
_cachedKey = String.Format("{0}:{1}:{2}", GetType().Name, path, sbCachedKey.ToString());
}
if (!String.IsNullOrWhiteSpace(_cachedKey) && filterContext.HttpContext.Cache[_cachedKey] != null)
{
filterContext.Result = (ActionResult)filterContext.HttpContext.Cache[_cachedKey];
}
else
{
base.OnActionExecuting(filterContext);
}
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (!String.IsNullOrWhiteSpace(_cachedKey))
{
filterContext.HttpContext.Cache.Add(_cachedKey, filterContext.Result, null,
DateTime.UtcNow.AddSeconds(Duration), Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
base.OnActionExecuted(filterContext);
}
}
attributo di utilizzo
[OutputCacheComplex(typeof(DatacarMonitorSearchCriteriaModel), Duration = OutputCacheDurationInSeconds, Location = OutputCacheLocation.Server)]
public async Task<JsonNetResult<DatacarMonitorDetailModel>> ReadMonitorDetailsJson([DataSourceRequest] DataSourceRequest request, DatacarMonitorSearchCriteriaModel criteria)
{
//some really complicated code here
}
con questo nuovo un ttribute, è possibile specificare quale tipo [s] utilizzare per la memorizzazione nella cache e la chiave di cache verrà calcolata in base ai valori di ciascuna delle sue proprietà.
-1
per oggetto, solo che funzionano bene:
[OutputCache(VaryByParam = "*", Duration = 60)]
Problemi correlati
- 1. Trasmissione di LinkedHashMap a un oggetto complesso
- 2. Recupera un oggetto complesso da ActionParameters
- 3. Costruire un oggetto (un po ') complesso
- 4. ext js - Collegamento ColumnModel a un oggetto JSON complesso
- 5. Passo oggetto con la proprietà complesso con servizio web
- 6. Convertire file Java oggetto complesso a JSON
- 7. Autowire a seconda della sottoclasse
- 8. Determinare se un oggetto JavaScript è un oggetto "complesso" o semplicemente una stringa
- 9. Passo Complesso JSON oggetto a un MVC 3 Azione
- 10. Dichiarare oggetto complesso di portata isolato
- 11. L'attributo del controller OutputCache varia in base al ruolo dell'utente? È possibile in .net MVC?
- 12. Come mappare un oggetto complesso con Automapper?
- 13. Knockout.js: Legatura per oggetto complesso
- 14. Utilizzando l'interfaccia IXmlSerializable sul grafico oggetto complesso
- 15. Ksoap2 Android: come specificare uno spazio dei nomi per le proprietà figlio di un oggetto complesso?
- 16. Associazione a una seconda proprietà se la prima è "indefinita"
- 17. Come filtrare un oggetto JSON complesso usando javascript?
- 18. Come passare un oggetto JSON complesso al controller ASP.net
- 19. Ordinamento di un oggetto JavaScript nome della proprietà
- 20. jquery flot, dimensione e colore che varia per ogni punto
- 21. Postgresql. CREATE CAST 'carattere che varia' a 'numero intero'
- 22. Condivisione di un oggetto complesso tra processi Python?
- 23. Estendere l'ereditarietà di `this` a metodi/proprietà di un` oggetto`
- 24. analisi di un complesso oggetto JSON utilizzando GSON in Java
- 25. Come posso salvare un oggetto Objective-C che non è un oggetto elenco di proprietà o esiste un modo migliore per farlo rispetto a un elenco di proprietà?
- 26. Associazione della proprietà controllata di un oggetto CheckBox all'interno di un oggetto modello
- 27. Aggiunta dinamica di proprietà a un oggetto dinamico?
- 28. Associazione di un oggetto TextBlock a proprietà di una finestra
- 29. PropertyGrid proprietà readonly a livello di oggetto
- 30. Può un parametro QueryString essere legato ad un oggetto complesso se l'oggetto complesso dispone di colata implicita da stringa
Qual è il tuo metodo _types.AtLeastOnce() ?? – leen3o
@ leen3o Il metodo 'AtLeastOnce (Expression)' è solo un metodo di estensione Enumerable equivalente al LINQ 'Any (Expression)' –