Jquery ajax不会调用Web API Post Type操作

时间:2018-05-26 18:15:47

标签: asp.net-web-api jquery-ajaxq

这就是我的网络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资源   'http://localhost:58782/api/Appointments/BookAppointment'。

我的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配置中只有默认路由。 请告诉我我做了什么样的错误,它无法正常工作。感谢

1 个答案:

答案 0 :(得分:0)

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

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

所以没有给出必要的部分(email / 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。请参阅this链接。