Search code examples
c#apihttphttpexception

C# (500) Internal Server Error overrides original exception


I am creating an API on C#. When I have an exception I try to send back a helping message, but "The remote server returned an error: (500) Internal Server Error." overrides the original one.

The code on server side is this one

 string authHeader = actionContext.Request.Headers.Authorization.Parameter;

        if (authHeader.Equals(ATOKEN) || authHeader.Equals(BTOKEN))
        {
            //goal reached. Token Authentication is valid.  
        }
        else
        {
            throw new HttpException("Invalid User!");                                  
        }

When I try to handle the exception on client side a cannot find the message "Invalid User"!

Any suggestions on this?


Solution

  • Rather use HttpResponseException like below

        var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            ReasonPhrase = "Invalid User!"
        };
        throw new HttpResponseException(resp);