throw exception from onactionexecuting in base controller

kikme
kikme
32 Points
11 Posts

In asp.net core api application, we have base controller from where all application's controllers inherited.
And in base controller overriding onActionExecuting method.
On the basis of few condition, want to throw exception and that can be handle from action or any global middle-ware:

public class BaseController<TService> : Controller
{
    public BaseController(TService service, ILogger logger)
    {
        Service = service;
        Logger = logger;
    }

    public CurrentUser CurrentUser { get; set; }

    protected TService Service { get; }

    protected ILogger Logger { get; }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var identityClaims = context.HttpContext.User;

        CurrentUser = new CurrentUser();
        CurrentUser.UserEmail = identityClaims.Claims.SingleOrDefault(c => c.Type == "email")?.Value;
        
        if(String.IsNullOrEmpty(CurrentUser.UserEmail))
        {
            throw new Exception("Unauthorized")
        }
    }
}

But not catching on action Try ... Catch block.

Views: 33
Total Answered: 2
Total Marked As Answer: 0
Posted On: 16-May-2020 06:03

Share:   fb twitter linkedin
Answers
nicehai
nicehai
2 Points
1 Posts
         
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
   app.UseExceptionHandler(app =>
   {
        app.Run(async context =>
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "text/html";

            await context.Response.WriteAsync("<html lang=\"en\"><body>\r\n");
            await context.Response.WriteAsync("ERROR!<br><br>\r\n");

            var exceptionHandlerPathFeature =
                context.Features.Get<IExceptionHandlerPathFeature>();

            // Use exceptionHandlerPathFeature to process the exception (for example,
            // logging), but do NOT expose sensitive error information directly to
            // the client.

            if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
            {
                await context.Response.WriteAsync("File error thrown!<br><br>\r\n");
            }

            await context.Response.WriteAsync("<a href=\"/\">Home</a><br>\r\n");
            await context.Response.WriteAsync("</body></html>\r\n");
            await context.Response.WriteAsync(new string(' ', 512)); // IE padding
        });
    });
    app.UseHsts();
}

We can sue middle-ware in startup.cs as:

 

Posted On: 26-May-2020 00:56
Smith
Smith
Participant
504 Points
127 Posts
         
app.UseExceptionHandler(a => a.Run(async context =>
            {
                var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                var exception = exceptionHandlerPathFeature.Error;
                var result = JsonConvert.SerializeObject(new ResponseModel
                {
                    Code = exception.HResult,
                    Message = exception.Message
                });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync(result);
            }));
public class ResponseModel
    {
        public string Message { get; set; }
        public int Code { get; set; }
    }
Posted On: 28-May-2020 23:50
 Log In to Chat