将缓存的MVC动作限制为Request.IsLocal

本文关键字:Request IsLocal 缓存 MVC | 更新日期: 2023-09-27 18:18:38

我有一个带有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,或方法未找到等。但如果是请求。本地你会得到缓存的结果。

如果不是缓存,这将运行得很好,但我正在努力寻找一种方法来组合请求。IsLocal和caching

可能相关的额外信息:

我通过c#调用GetStuffData,通过获取一个json对象来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();
}

将缓存的MVC动作限制为Request.IsLocal

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

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