[英]Javascript ajax call can't hit my Web API controller page. Can't seem to get the url correct
我有一個注冊頁面,我試圖將輸入字段保存到Users表中的新記錄中。
<button class="btn-u" type="submit"
onclick="submitclicked()">Register</button>
點擊被拾起,我可以在我的.js上找到斷點
function submitclicked() {
insertNewUser();
ko.applyBindings({ insertNewUser: insertNewUser });
};
function Person() {
this.FirstName = firstname();
this.LastName = lastname();
this.Email = email();
this.Password = password();
}
var insertNewUser = function () {
var person = new Person();
var url = "/api/Home/addUser"
$.ajax({
url: url,
type: 'post',
data: person,
contentType: "application/json; charset=utf-8",
success: function (result) {
}
})
};
我的RegController.cs文件中也有一個斷點,但是它從未被命中。 這使我相信它永遠不會進入我的控制器。 我的控制器如下所示:
public class RegController : ApiController
{
//now insert these values into the DB
private static void addUser(Person item)
{
var db = new MyEntities();
try
{
User record = new User()
{
First_Name = item.FirstName,
Last_Name = item.LastName,
Email = item.Email,
Password = item.Password
};
db.User.Add(record);
db.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
}
在解決方案資源管理器中,它進入RegController.cs> RegController> Person> addUser(Person):無效。
我已經嘗試過我能想到的針對ajax url的所有其他選項,但均未成功。 有人可以告訴我我做錯了什么嗎?
編輯:添加RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
有幾個問題:
控制器中的動作是靜態的。
控制器中的操作是私有的而不是公開的。
您使用的路由指向錯誤的端點(使用路由調試器或API幫助來查看正確的端點)。
需要考慮的一些更新:
public class RegController : ApiController
{
//now insert these values into the DB
public void addUser(Person item)
{
...
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
}
對於jquery請求:
var insertNewUser = function () {
var person = new Person();
var url = "/api/Reg"
$.ajax({
url: url,
type: 'post',
data: person,
contentType: "application/json; charset=utf-8",
success: function (result) {
}
})
};
假設這是一個普通的Web api v2應用程序,如果您運行Web應用程序並單擊API鏈接,它將向您顯示如何配置路由。
旁注:在調試Web api以利用以下包時,我發現它很有用:
Install-Package WebApiRouteDebugger
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.