asp.net-web-apijquery-ajaxq

Web API Post Type action is not getting called by jquery ajax


This is how my web api action look like.

[System.Web.Http.HttpPost, System.Web.Http.Route("BookAppointment/{email}/{id}")]
public System.Net.Http.HttpResponseMessage BookAppointment(string email, int id = 0)
{
    System.Net.Http.HttpResponseMessage retObject = null;

    if (id > 0 && email!="")
    {
        UserAppointmentService _appservice = new UserAppointmentService();
        bool success = _appservice.BookAppointment(email,id);

        if (!success)
        {
            var message = string.Format("error occur for updating data", id);
            HttpError err = new HttpError(message);
            retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
            retObject.ReasonPhrase = message;
        }
        else
        {
            retObject = Request.CreateResponse(System.Net.HttpStatusCode.OK, "SUCCESS");
        }
    }
    else
    {
        var message = string.Format("doc id and emial can not be zero or blank");
        HttpError err = new HttpError(message);
        retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
        retObject.ReasonPhrase = message;

    }
    return retObject;
}

This is my jquery ajax code which suppose to call web api action but throwing error. the error is

No HTTP resource was found that matches the request URI 'http://localhost:58782/api/Appointments/BookAppointment'.

My jquery ajax code as follows.

    $('#tblAppointments').on('click', '#btnbook', function () {
        var docid = $(this).closest('tr').find("input[id*='hdndocid']").val();
        var email = $(this).closest('tr').find("input[id*='hdnpatientemail']").val();

        var baseurl = '@ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment';
        // + encodeURIComponent(email) + '/' + docid;
        alert(baseurl);
        $.ajax({
            url: baseurl,
            type: 'POST',
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify({ email: encodeURIComponent(email), id: docid}),
            success: function (data, textStatus, xhr) {
                console.log(data);

            },
            error: function (xhr, textStatus, errorThrown) {
                var err = eval("(" + xhr.responseText + ")");
                alert('Error ' + err.Message);
                console.log(textStatus);
            }

        }).done(function () {


        });
    });

I have only default route in web api config. Please tell me what kind of mistake i have done for which it is not working. thanks


Solution

  • There are more problems with your code so I will try to explain them step by step.

    1.Based on the code you have provided, you must have decorated your controller with a route like

    [RoutePrefix("api/appointments")] 
    

    in order to correctly call the BookAppointment method. If you decorate your controller with this attribute, then you can simply call

    http://localhost/api/appointments/BookAppointment/testemail@domain.com/1
    

    and the method would be 100% called.

    2.The following code:

    var baseurl = '@ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment';
                // + encodeURIComponent(email) + '/' + docid;
    

    translates into something like

    http://localhost/api/Appointments/BookAppointment
    

    so the necessary part (email/id) are not given (that's why the error message is given).

    3.The javascript code makes a POST with JSON in body but your API is not accepting JSON body. I recommend that you create a separate class like this:

     public class BookAppointmentRequest
      {
        public string Email { get; set; }
        public int ID { get; set; }
      }
    

    And after that, you modify the method in order to specify that you are accepting data from body.

    [HttpPost, Route("BookAppointment")]
    public HttpResponseMessage BookAppointment([FromBody] BookAppointmentRequest request)
    

    After that, you can simple make a POST to api/Appointments/BookAppointment with the JSON from your javascript code.

    1. I recommend you to use IHttpActionResult instead of HttpResponseMessage. See this link.