Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exception Handling in ASP.NET Web API giving me errors after HttpRequestException

So here is one of my actions.

 public Customers GetCustomer(int id)
    {
        var customer = _context.Customers.SingleOrDefault(c => c.Id == id);

        if (customer == null)
            throw new HttpRequestException(HttpStatusCode.NotFound);
        return customer;
    }

This part of the code

        throw new HttpRequestException(HttpStatusCode.NotFound);

throws the following error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        cannot convert from 'System.Net.HttpStatusCode' to 'String'

Also, in one of my other methods, same error is being thrown on the following.

        throw new HttpRequestException(HttpStatusCode.BadRequest);

This is an Api controller and I am not sure why these errors are being thrown. I looked up the syntax on the microsft website and it seems to be correct. It can be seen here:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling

>Solution :

I think that you are looking for is HttpResponseException and not HttpRequestException. If so, you can do it as below:

throw new HttpResponseException(HttpStatusCode.NotFound);

This works, because as you can see in documentation, there is a constructor for that class that takes one parameter of type HttpStatusCode. On the other hand, as you can see here, this is not true for HttpRequestException.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading