0

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

Thomas
  • 33,544
  • 126
  • 357
  • 626

1 Answers1

0

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.
  • i have not checked your code but i belive it will work. thanks – Thomas May 26 '18 at 19:21
  • see this line var baseurl = '@ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment'; // + encodeURIComponent(email) + '/' + docid; i tried passing data as query string when it did not work then i comment this line encodeURIComponent(email) + '/' + docid; – Thomas May 26 '18 at 19:23
  • A request...can you please provide a sample web api which accept few param like int, string etc also show how to call that action with jquery ajax where type will be post not get. – Thomas May 26 '18 at 19:24
  • this article help to pass multiple data to post type action https://www.c-sharpcorner.com/article/invoking-webapi-controller-action-with-multiple-parameters-in-cors/ it show we need to use 3rd party library. – Thomas May 26 '18 at 19:25
  • @Thomas Do you need help with GET or POST requests? You do not need 3rd party libraries. – Florin-Constantin Ciubotariu May 26 '18 at 19:37
  • I need help for post request where i will pass multiple parameter to action without any viewmodel class as argument. – Thomas May 26 '18 at 19:55
  • I do not want to use this [FromBody] BookAppointmentRequest request rather i want multiple param will be there like int id, string email for action. can you post anything similar like. thanks – Thomas May 26 '18 at 19:56
  • my action would look like this public System.Net.Http.HttpResponseMessage BookAppointment(string email, int id = 0) and i will pass json form id and email from client side uisng jquery ajax. so how could i do it without 3rd party library. help would be appreciated. thanks – Thomas May 26 '18 at 19:58
  • Indeed, by default, you can not map those values without having a wrapper in a POST request. – Florin-Constantin Ciubotariu May 26 '18 at 20:13
  • using 3rd party i can do it whose link i share here. please check. thanks – Thomas May 26 '18 at 20:16
  • Why you recommend to use IHttpActionResult instead of HttpResponseMessage....any advantage is there? – Thomas May 27 '18 at 10:15
  • The MSDN explains some benefits of using IHttpActionResult. You can also check this link from SO. https://stackoverflow.com/questions/21758615/why-should-i-use-ihttpactionresult-instead-of-httpresponsemessage – Florin-Constantin Ciubotariu May 27 '18 at 10:22