Yes, I’m still rewriting an existing ASP.NET Web API application to ASP.NET Core.
I ported an existing action method where I was using response caching. I previously ported other action methods that used caching but this one was a little bit different because I had to take the querystring values into account for the caching.
This is easily arranged by specifying the name of the query string parameter using the VaryByQueryKeys property on the ResponseCache attribute.
[HttpGet()] | |
[ResponseCache(Duration =3600, Location = ResponseCacheLocation.Any, VaryByQueryKeys=new string[]{"name"})] | |
public async Task<ActionResult<User>> GetUserInfo(string name) | |
{ | |
var user = await _userService.FindByName(name); | |
if (user == null) | |
{ | |
return NotFound(); | |
} | |
return user; | |
} |
Small tip: If you want to take all query string parameters into account, you can use “*” as a single value.
When I tried to call this method I got a 500 error. Inside the logs I noticed the following error message:
InvalidOperationException: 'VaryByQueryKeys' requires the response cache middleware.
Although caching seemed to work for other scenario’s, when I used the VaryByQueryKeys property I had to add the response caching middleware.
Here is my Startup.ConfigureServices():
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddResponseCaching(); | |
//Removed other code | |
} |
And my Startup.Configure()
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
// UseCors must be called before UseResponseCaching | |
// app.UseCors("myAllowSpecificOrigins"); | |
app.UseResponseCaching(); | |
//Removed other code | |
} |