我已經查看了幾個線程,現在他們想從ASP項目中的JavaScript調用C#方法。我無法弄清楚我做錯了什麼。這裏是我的C#類:404 Not Found從ASP中的JavaScript調用Http方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
namespace Selfservice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public String GetCredentials()
{
return User.Identity.Name.ToString();
}
}
}
,這裏是JavaScript的我想呼籲:
window.onload = function() {
LiveSearch();
getCredentials();
//FetchAllUsers();
};
function getCredentials() {
$.ajax({
type: 'POST',
url: '@Url.Action("GetCredentials", "Home")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf8',
data: JSON.stringify(""),
success: function (cred) {
alert(cred);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
我不斷收到404 Not Found狀態回來了。這是一個ASP網站,部署在我的工作場所服務器上的IIS上。我們正在使用Windows身份驗證,因此我希望獲得登錄的人員的憑據,並將其存儲爲以後的其他內容。
我在我的智慧結束在這裏。任何人有任何想法?
簡單,你已經在你的action方法中聲明瞭'[HttpGet]',同時你從jQuery'POST'它... – kayess
@kayess我不是JS JS,但是我看到的一些答案說:是問題的答案。切換到「獲取」不能解決這個問題。 – OmniOwl
你是否試過「/ Home/GetCredentials」作爲url?也像提到的更改GET去除contentType並將dataType更改爲「text」作爲您的控制器不返回json – Kris