[英]Restricting a cached MVC action to Request.IsLocal?
我有一个带有OutputCache的MVC操作,因为我需要缓存数据以最小化对myService的调用。
[HttpGet]
[OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient, VaryByParam = "myVariable")]
public JsonResult GetStuffData(string myVariable)
{
if (Request.IsLocal)
{
return myService.CalculateStuff(myVariable)
}
else
{
return null;
}
}
我只希望从运行它的服务器上可以访问它,因此Request.IsLocal。
这可以正常工作,但是如果有人远程访问GetStuffData,则它将返回null,并且null将被缓存一天……从而使该特定的GetStuffData(myVariable)一天都没有用。
同样,如果首先在本地调用它,则外部请求将接收缓存的本地数据。
有没有一种方法可以将整个函数限制为Request.IsLocal而不只是返回值?
因此,例如,如果从外部访问它,则只会得到404,或者找不到方法等。但是,如果它是Request.Local,则可以得到缓存的结果。
如果不是用于缓存,那么它将运行得很好,但是我正在努力寻找一种将Request.IsLocal和缓存结合起来的方法。
可能相关的额外信息:
我通过这样的json对象通过C#调用GetStuffData到getcached StuffData ...(直接调用该操作永远不会导致它被缓存,因此我切换到模拟webrequest)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToGetStuffData);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
您可以使用自定义授权过滤器属性,例如
public class OnlyLocalRequests : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsLocal)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
return false;
}
return true;
}
}
并将您的动作装饰为
[HttpGet]
[OnlyLocalRequests]
[OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient, VaryByParam = "myVariable")]
public JsonResult GetStuffData(string myVariable)
{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.