user4650842
user4650842

Reputation:

C# Web API 405 Error on GET

I'm brand new to restful APIs after a decade on desktop development. I'm a little confused as to why I am getting a 405 attempting a GET for a controller.

My controller:

public class ApplicantsController : ApiController
{

    /// <summary>
    /// Gets the details of the applicant and their application
    /// </summary>
    /// <param name="applicantID">The ID of the applicant to get the most recent application and details for</param>
    /// <returns></returns>
    public HttpResponseMessage Get(int applicantID)
    {
        try
        {
            using (DbQuery query = new DbQuery("SELECT * FROM Applicants AS A WHERE A.ID = @ApplicantID",
                new DbParam("@ApplicantID", applicantID)))
            {
                using (DataTable data = query.ExecuteDataTable())
                {
                    if (data.Rows.Count > 0)
                    {
                        Applicant applicant = new Applicant(data.Rows[0]);

                        return new HttpResponseMessage()
                        {
                            Content = new StringContent(applicant.ToJson(), Encoding.UTF8, "text/html")
                        };
                    }
                }
            }

            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }
        catch (Exception ex)
        {
            Methods.ProcessException(ex);
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
    }

    public HttpResponseMessage Post(Applicant applicant)
    {
        if (applicant.Save())
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, applicant);
            string uri = Url.Link("DefaultApi", new { id = applicant.ID });
            response.Headers.Location = new Uri(uri);

            return response;
        }

        return Request.CreateResponse(HttpStatusCode.InternalServerError, "Error saving applicant");
    }
}

}

I have the same default routing in my WebApiConfig and confirmed that the way my controller is written it matches a standard Web API 2 controller with read, write, update methods. I've tried using DefaultAction, I've tried decorating methods with [HttpGet] and [AcceptVerbs]. Whenever I try to access the Get through either a browser myself or through ajax, I get a 405 (method not allowed).

Ajax test:

        $("#TestGetApplicantButton").click(function (e) {
            e.preventDefault();
            alert("Getting Applicant...");

            $.ajax({
                type: "GET",
                url: "/api/Applicants/108",
                contentType: "application/json; charset-utf-8",
                dataType: "json",
                success: function (data) {
                    $("#ResponseDiv").html(JSON.stringify(data));
                },
                failure: function (errMsg) {
                    alert(errMsg);
                }
            });
        });

Ajax works perfectly for all of the other controllers, showing the data returned (example: Tests Work! and it even calls the Post method on this controller just fine. Yet I can't get my Get to work. I don't see where I could be going wrong.

My routing:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

I've googled and checked here, but everyone seems to only have issues with POST, PUT, or DELETE, so I haven't found an answer for this. I've also tried removing the POST method in the controller - that gets me a 404 instead (not from my 404, I confirmed the code doesn't execute), which suggests for some reason the routing can't find my get method at all.

Upvotes: 4

Views: 172

Answers (1)

Jason Carter
Jason Carter

Reputation: 96

You need to add a default value to your applicantID parameter, since your route has the first parameter marked as RouteParameter.Optional.

public HttpResponseMessage Get(int applicantID = 0)

This will ensure that your Get method signature matches your "DefaultApi" route.

Upvotes: 4

Related Questions