asp.net-web-api - 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 配置中只有默认路由。请告诉我我犯了什么样的错误而它不起作用。谢谢
解决方案
您的代码存在更多问题,因此我将尝试逐步解释它们。
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。
- 我建议您使用 IHttpActionResult 而不是 HttpResponseMessage。请参阅此链接。
推荐阅读
- javascript - ReactJS how do i save input file multiple image base64
- node.js - 在这种情况下,以下 npm 文档中的“全局运行 npm 包”是什么意思?
- log4j2 - 带有控制台的 log4j2 xml 配置
- c - 使用 O_CREAT O_WRONLY :如何获取文件中的当前位置并在末尾附加数据?
- javascript - 如何在使用react的useeffect返回语句中使用react.usecallback?
- c# - 如何在 C# 中使用 restapi 从 github 为用户(人)获取数据?
- java - 如何根据页眉/页脚高度动态调整页边距
- r - 在闪亮的应用程序中显示变量的摘要(summary())
- android - 如何仅在 Ubuntu 上安装 Android Studio 命令行工具
- hyperlink - Select2 - 带有外部链接的选项项目中的自定义输入字段