404 Not Found在ASP中从JavaScript调用Http方法

时间:2017-04-11 13:29:48

标签: javascript c# asp.net ajax

我现在看了几个线程,他们想在ASP项目中用JavaScript调用C#方法。我无法弄清楚我做错了什么。这是我的C#类:

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=utf­8',
        data: JSON.stringify(""),
        success: function (cred) {
            alert(cred);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

我一直收到404 Not Found状态。它是在我的一个工作场所服务器上部署在IIS上的ASP站点。我们正在使用Windows身份验证,因此我希望获取登录的用户凭据并在以后将其存储为其他内容。

我的智慧在这里结束了。有人有任何想法吗?

1 个答案:

答案 0 :(得分:2)

您是否曾尝试将“/ Home / GetCredentials”作为网址?同样如上所述,更改为GET方法,删除contentType并将dataType更改为“text”,因为您的控制器未返回JSON。