Reputation: 7788
I've got a WebApi endpoint with an [Authorized]
attribute. I did not configure any additional policies or anything.
[Authorized]
[Route("foo")]
public async Task<IActionResult> Foo(FooModel model)
{
// .......
}
When I try to hit this endpoint and I'm not authenticated I'll get a 404 response w/o content.
What I want to get: A customized response type with a 401 statuscode. How can I do that?
Upvotes: 0
Views: 504
Reputation: 7190
You can add following code in your Startup
Class:
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});
Your action:
[Authorize]
public async Task<IActionResult> Foo(FooModel model)
{
// ...
}
By the way,this will cause you can't redirect to your Login page, you can set it only works for api
, like the following:
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api")
&& context.Response.StatusCode == StatusCodes.Status200OK)
{
context.Response.Clear();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
}
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
};
});
Upvotes: 2
Reputation: 1529
Try using [Route]
to make sure you are calling the function correctly
[Authorized]
[Route("Foo")]
public async Task<IActionResult> Foo(FooModel model)
{
}
Upvotes: 0