locked
Set content when returning result in ExceptionFilterAttribute RRS feed

  • Question

  • User-585144208 posted

    Hi

    I want to return 401 when handling exception in my app:

    public override void OnException(ExceptionContext context)
    {
    if (context.Exception is UnauthorizedTransactionSystemException)
    {
    
    var response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent("Authorization exception while accessing ST."),
    ReasonPhrase = "User is not authorized. Please contact your administrator."
    };
    
    context.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase =
    "User is not authorized. Please contact your administrator.";
    
    }
    }

    I want to set the content of the result as I can set it with HttpResponseMessage, but I do not know how. Here is how I set HttpResponseMessage:

     var response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                                       {
                                           Content = new StringContent("Authorization exception while accessing."),
                                           ReasonPhrase = "User is not authorized. Please contact your administrator."
                                       };

    Thursday, October 3, 2019 11:38 AM

All replies

  • User711641945 posted

    Hi b.dev,

    If you use ASP.Net Core,you need to know that Authorization filters run first in filters pipeline when you add Authorize attribute.If you fail to authorize,you would get 401 by default and it would not get into the Exception Filter.

    I find you use UnauthorizedTransactionSystemException.Did you custom Authorization and not use default Authorization?

    Reference:

    https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.2#filter-types

    Best Regards,

    Rena

    Friday, October 4, 2019 9:53 AM
  • User-585144208 posted

    Hi

    We do not use ASP.NET authorization. We call a service inside the action that I want to apply the filter and that service might throw excpetion which indicates unauthorized exception. 

    Friday, October 4, 2019 10:11 AM
  • User711641945 posted

    Hi b.dev,

    You could change your code like below:

    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
                
            if (context.Exception is UnauthorizedAccessException)
            {
                var response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Authorization exception while accessing ST."),
                    ReasonPhrase = "User is not authorized. Please contact your administrator."
                };
                context.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "User is not authorized. Please contact your administrator.";
                context.Result = new HttpResponseMessageResult(response);
                base.OnException(context);
            }
        }      
    }
    public class HttpResponseMessageResult : IActionResult
    {
        private readonly HttpResponseMessage _responseMessage;
    
        public HttpResponseMessageResult(HttpResponseMessage responseMessage)
        {
            _responseMessage = responseMessage; // could add throw if null
        }
    
        public async Task ExecuteResultAsync(ActionContext context)
        {
            context.HttpContext.Response.StatusCode = (int)_responseMessage.StatusCode;
            using (var stream = await _responseMessage.Content.ReadAsStreamAsync())
            {
                await stream.CopyToAsync(context.HttpContext.Response.Body);
                await context.HttpContext.Response.Body.FlushAsync();
            }
        }
    }

    Result:

    Best Regards,

    Rena

    Tuesday, October 8, 2019 7:53 AM