How to set HTTP cache-control from .net web service?
I have a legacy C# web service (class inheriting System.Web.Services.WebService
) with a series of WebMethods like so:
[WebMethod, SoapHeader("header", Direction=SoapHeaderDirection.In)]
[SoapDocument开发者_运维百科Method("http://www.myservices.com/Services/1.1#getMediaMetadata")]
public MediaMetadata getMediaMetadata(string id)
{
return new MediaService().GetMetadata( id );
}
I am attempting to set the cache-control header on the response via HttpResponse.Cache.SetMaxAge
. Executing the service yields a default header:
Cache-Control:private, max-age=0
I replaced the standard Cache.SetMaxAge
with a hardcoded header:
HttpContext.Current.Response.AddHeader( "Cache-Control", "private, max-age=" + (int)ttl.TotalSeconds );
Yet still the web server responds with the default Cache-Control. I suspect ASP.NET web services are mucking this up after execution of the web method. The suggestion below to use the CacheDuration attribute of WebMethod is not applicable in my scenario.
Any advice?
[WebMethod(CacheDuration=60), SoapHeader("header", Direction = SoapHeaderDirection.In)]
SoapDocumentMethod("http://www.myservices.com/Services/1.1#getMediaMetadata")]
public MediaMetadata getMediaMetadata(string id)
{
return new MediaService().GetMetadata( id );
}
Add this attribute to your Should do the trick.
If you specifically wanted to access the context then
Context.Response.Cache.SetMaxAge(TimeSpan.FromSeconds(60));
You will be safe to access the context unless it's null. A simple check will solve this for you
精彩评论