0
votes

I am moving some code to a Web API, and I want to only accept requests that are perfect (postdata in order, all headers in order, etc.), and deny other requests. Right now I have it so that if a perfect requests comes in then it returns the correct output with a 200 OK status code, and if a malformed requests comes in (aka a not properly spoofed request) then it returns a 404 NOT FOUND.

The functions in my controller all have a parameter with the FromBody attribute, so that means it works fine if the request uses the content-type "application/json", but when a requests comes in with another content type then it automatically returns a 415 Unsupported Media Type status code. What I want is to basically "hide" all my endpoints and only return something other than a 404 status code when the request is perfect. So I want to change the returned 415 Unsupported Media Type status code with a 404 status code.

1
415 means that the server did not understand the request (like if you sent XML when JSON was expected), it wouldn't make a lot of sense to turn that into a 404 - and you win absolutely no security by this change - Camilo Terevinto
Only my program should be allowed to send valid requests and I am predicting people will reverse engineer my application and try to send their own request. - nevsnirG

1 Answers

1
votes

You can add a custom middle ware to achieve that :

        app.Use(async (context, next) =>
        {
            await next.Invoke();

            if (context.Response.StatusCode == StatusCodes.Status415UnsupportedMediaType)
            {
                context.Response.StatusCode = StatusCodes.Status404NotFound;
                await context.Response.WriteAsync("404 not found");
            }
        });

Make sure to configure it at appropriate place in your middle ware pipeline.