Reputation: 11336
I am trying to configure the handling of certain HTTP Response Status Codes in the middleware of my ASP.NET Core 2.2 MVC app using this example code from Microsoft docs:
app.UseStatusCodePages(async context =>
{
context.HttpContext.Response.ContentType = "text/plain";
await context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
But it displays an error for HttpContext
saying
'IApplicationBuilder' does not contain a definition for 'HttpContext' and no accessible extension method 'HttpContext' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)
I see that context
is of type Microsoft.AspNetCore.Diagnostics.StatusCodeContext which has a HttpContext property. Why is it not recognizing HttpContext?
P.S. I tried installing these NuGet packages to no avail:
Microsoft.AspNetCore.Diagnostics
Microsoft.AspNetCore.Diagnostics.Abstractions
Microsoft.AspNetCore.Http
Microsoft.AspNetCore.Http.Abstractions
Microsoft.AspNetCore.Http.Extensions
Microsoft.AspNetCore.Http.Features
Upvotes: 5
Views: 8538
Reputation: 3739
You are missing some using statements. Sometimes IntelliSense doesn't quite pick up on where you want to go (statement is probably ambiguous). You could be more specific and code it like this:
async (StatusCodeContext ctx) => ...
Which, in your case would most likely let IntelliSense suggest some using statements that you need, after which you can replace with:
async ctx => ...
again, and it should probably work.
Upvotes: 0
Reputation: 11336
Discovered the issue ... it's a bit odd: When I check Intellisense on the first instance of HttpContext
it doesn't offer any suggestions for using
statements, but when I do it on any of the other instances it suggests adding a reference to Microsoft.AspNetCore.Http
, which fixes it.
I'm not sure why it's not finding that suggesting when I check the first HttpContext
.
Upvotes: 6
Reputation: 4443
You need to return a Task
from your lambda expression for the compiler to recognize the correct overload.
You are trying to use this overload:
UseStatusCodePages(IApplicationBuilder, Func<StatusCodeContext,Task>)
But since your lambda expression doesn't return a Task
, the compiler is using this overload:
UseStatusCodePages(IApplicationBuilder, Action<IApplicationBuilder>)
Consequently, your context
variable is actually referring to an instance of IApplicationBuilder
, not StatusCodeContext
.
Returning the Task
from WriteAsync
should do the trick:
app.UseStatusCodePages(context =>
{
context.HttpContext.Response.ContentType = "text/plain";
return context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
Upvotes: 0