Bhavesh Jadav
Bhavesh Jadav

Reputation: 705

Wrong API url in ASP.NET Core

I have API controller in ASP.NET Core application as following.

[Route("api")]
public class UserController : Controller
{
    [HttpGet("{userName}/product_info")]
    public IActionResult GetProductInfo(string userName)
    {
        List<ProductInfo> productInfos = _repo.GetProductInfoByUserName(userName);
        if (productInfos.Count > 0)
            return Ok(productInfos);
        else
            return BadRequest("Unable to process requrest");
    }
}

I can call above API using /api/{username}/product_info. I have am using UseStatusCodePagesWithRedirects() to redirect to 404 page when user enters the wrong url. The problem here is that when I use wrong API url such as /api/{username}/product_o. It redirects to 404 page and returns status code of 200. I am using this API with angular.js. Since API returns 404 page on wrong URL with status code of 200, error function of then method of $http is never called and in response.data I get the HTML of 404 page. How do I return status code of 404 when wrong API URL is called and return normal 404 page when wrong NON API URL is called? Below is the screen shot of what I am getting when I call wrong API URL. enter image description here

Based on @Daboul suggestion and solution on this link Adding following part in configure method of startup.cs works.

Func<HttpContext, bool> isApiRequest = (HttpContext context) => context.Request.Path.ToString().Contains("/api/");
app.UseWhen(context => !isApiRequest(context), appBuilder =>
{
     appBuilder.UseStatusCodePagesWithRedirects("~/Error/{0}");
});

Upvotes: 3

Views: 1511

Answers (1)

Daboul
Daboul

Reputation: 2733

I believe that by using middlewares like UseStatusCodePages() or UseStatusCodePagesWithRedirects(), you are deciding to actually return a proper HTML page containing the error code (which require to send to the browser a code 200) instead of returning the code in itself. It's usually considered as a good practice in terms of security. What you are experiencing seems logical to me. Maybe, I'm not sure it would help in your case, what you could do is limit the usage of UseStatusCodePagesWithRedirects() to all the controllers but the api one using a UseWhen(), so that any wrong URL on this particular "/api/" controller would still returns 404? Or parse the answer in your angular to detect if any error occured.

Upvotes: 3

Related Questions