【问题标题】:Restricting a cached MVC action to Request.IsLocal?将缓存的 MVC 操作限制为 Request.IsLocal?
【发布时间】:2015-10-20 20:18:29
【问题描述】:

我有一个带有 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 和缓存。

可能相关的额外信息:

我通过 C# 调用 GetStuffData 以通过获取这样的 json 对象来获取缓存的 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();
}

【问题讨论】:

    标签: c# asp.net-mvc outputcache


    【解决方案1】:

    您可以使用自定义授权过滤器属性,如

    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)
    {}
    

    【讨论】:

    • 看起来不错,但不太好用。如果我第一次从外部访问它,我会得到 404(很棒)。如果我在本地访问它,我会得到结果(很好)。如果我然后从外部访问它,我会得到缓存的结果。所以还是个问题
    • @mejobloggs 我已经更新了OnlyLocalRequests 类。
    • 优秀。不返回 404 但在我从外部访问时将我发送到登录页面,但这很好。一切正常
    猜你喜欢
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    相关资源
    最近更新 更多