If I return StatusCode(403)
or any other error code from an endpoint, any configuration of app.UseStatusCodePages<whatever>
will be ignored.
I believe this is because the StatusCode(<whatever>)
will automatically create a result object, and UseStatusCodePages
only kicks in if there is an error status code and no content.
So how do I set a status code result in an IActionResult type endpoint and then return without setting any content so that UseStatusCodePages
will handle the job of providing a suitable resonse?
CodePudding user response:
As far as I know, the UseStatusCodePages will just be fired when the action result is the StatusCodeResult.
If you put some value inside the status codes, it will return the object result which will not trigger the UseStatusCodePages.
So I suggest you could directly use StatusCodeResult(403)
, then if you want to put some value to the StatusCodeResult, I suggest you could put it inside the httpcontext's item.
More details, you could refer to below codes:
public IActionResult OnGet()
{
HttpContext.Items.Add("test","1");
return StatusCode(403);
}
Program.cs:
app.UseStatusCodePages(async statusCodeContext =>
{
var status = statusCodeContext.HttpContext.Items["test"];
// using static System.Net.Mime.MediaTypeNames;
statusCodeContext.HttpContext.Response.ContentType = Text.Plain;
await statusCodeContext.HttpContext.Response.WriteAsync(
$"Status Code Page: {statusCodeContext.HttpContext.Response.StatusCode}");
});
Result:
CodePudding user response:
The issue was that I have the ApiController
attribute on the endpoint controller. One of the things this attribute does is to automatically create a ProblemDetails
response body for any failed requests, and it is this that prevents UseStatusCodePages
from having any effect.
The solution is to either remove the ApiController
attribute if you do not require any of its features, or alternatively its behaviour of automatically creating ProblemDetails
responses can be disabled using the following configuration in Program.cs
(or Startup.cs
in old style projects).
builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
{
options.SuppressMapClientErrors = true;
});