-2

I am using Web API project built with c# and I have a few controllers in it.

The controllers have their own constructor methods and in the constructor I am checking for authentication.

When the authentication is successful then it should execute the desired function, if not I want it to return JSON as invalid authorization.

I have the following code in place to do it:-

public class UsersController : Controller
    {
        private RM.Data.IUserData _userData;

        private String APIToken = AppConfig.GetConfigValue("APIToken");

        public UsersController()
        {
            if (match)
            {
                  // then execute function
            }
            else
            {
                  // stop execution
            }
        }

    }

I have tried the following things to stop the execution of the function.

return;
HttpResponse.End();
System.Threading.Thread.CurrentThread.Interrupt();
System.Threading.Thread.CurrentThread.Abort();
System.Web.HttpContext.Current.Response.Close();
Enviorment.Exit(0);
Enviorment.Exit(1);
Enviorment.Exit(-1);

Some terminate the app and the others let the api to continue processing.

I have about 50 API and cannot attach this function to each and every API. What can be done in this case.

Nothing worked for me from the above. Can you guys please help?

  • 4
    You are doing this all wrong. Research Filters. – Nkosi Mar 29 '18 at 14:28
  • 3
    This screams [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why are you doing authentication and heavy processing in a controller _constructor_? – maccettura Mar 29 '18 at 14:28

1 Answers1

3

in the constructor I am checking for authentication.

Well that's very wrong. You should use the [Authorize] attribute at your controller level at very minimum. If you are performing custom authorization logic then perform it in Authentication Filter in web api pipeline. See https://exceptionnotfound.net/the-asp-net-web-api-2-http-message-lifecycle-in-43-easy-steps-2/

Rahul
  • 76,197
  • 13
  • 71
  • 125