1

I´m trying to do this

throw new HttpResponseException(HttpStatusCode.Unauthorized); // 401

But this always returns 500(Internal server Error).

Example code:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Web.Http;


namespace Gral_WebAPI.Controllers
{
    [Produces("application/json")]
    public class LoginController : ApiController
    {
        [Microsoft.AspNetCore.Mvc.HttpGet]
        [Microsoft.AspNetCore.Mvc.Route("[action]")]
        public string GitTest()
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized); // 401
        }
    }
}

Anyone could help me?

1
  • 2
    why are you mixing .net core and classic asp.net? Commented Sep 20, 2018 at 17:41

1 Answer 1

2

You could use return StatusCode(401); instead. You should avoid using exceptions to control the flow of your application.

Do you have any middleware that's intercepting the exception and overriding the status code to 500?

Sign up to request clarification or add additional context in comments.

4 Comments

What is the URI you are using to access your action?
I´m calling this: localhost:59580/GitTest I´m using swagger and this is my Startup.cs codeshare.io/adjoEe
@MMachado, assuming you're using default routing rules the URI for this action is /Login/GitTest.
There is always some debate about whether an exception should be used in this way. Purest say an exception should be exceptional, but pragmatists use what works best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.