首页 > 解决方案 > Web API Post Type 操作没有被 jquery ajax 调用

问题描述

这就是我的 web api 操作的样子。

[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;
}

这是我的 jquery ajax 代码,假设调用 web api 操作但抛出错误。错误是

未找到与请求 URI“ http://localhost:58782/api/Appointments/BookAppointment ”匹配的 HTTP 资源。

我的 jquery ajax 代码如下。

    $('#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 () {


        });
    });

我在 web api 配置中只有默认路由。请告诉我我犯了什么样的错误而它不起作用。谢谢

标签: asp.net-web-apijquery-ajaxq

解决方案


您的代码存在更多问题,因此我将尝试逐步解释它们。

1.根据您提供的代码,您必须使用如下路线装饰您的控制器

[RoutePrefix("api/appointments")] 

为了正确调用 BookAppointment 方法。如果你用这个属性装饰你的控制器,那么你可以简单地调用

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

并且该方法将被100%调用。

2.以下代码:

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

翻译成类似的东西

http://localhost/api/Appointments/BookAppointment

所以没有给出必要的部分(电子邮件/ID)(这就是给出错误消息的原因)。

3.javascript 代码在正文中使用 JSON 进行 POST,但您的 API 不接受 JSON 正文。我建议您像这样创建一个单独的类:

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

之后,您修改该方法以指定您正在接受来自正文的数据。

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

之后,您可以使用 JavaScript 代码中的 JSON 简单地向 api/Appointments/BookAppointment 进行 POST。

  1. 我建议您使用 IHttpActionResult 而不是 HttpResponseMessage。请参阅链接。

推荐阅读