簡體   English   中英

將緩存的MVC操作限制為Request.IsLocal?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM