【问题标题】:404 Not Found calling Http Method from JavaScript in ASP404 Not Found 在 ASP 中从 JavaScript 调用 Http 方法
【发布时间】:2017-09-06 22:17:50
【问题描述】:

我现在查看了几个线程,他们希望在 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 身份验证,因此我想获取登录者的凭据并将其存储起来以供以后使用。

我有点不知所措了。有人有什么想法吗?

【问题讨论】:

  • 简单,你已经在你的action方法上声明了[HttpGet],而你在jQuery中POST...
  • @kayess 我不是 JS 奇才,但我看过的一些答案说这就是问题的答案。切换到“获取”并不能解决此问题。
  • 您尝试将“/Home/GetCredentials”作为 url 吗?也像提到的更改 GET 删除 contentType 并将 dataType 更改为“text”,因为您的控制器没有返回 json
  • @kayess 评论是解决方案。只需将[HttpGet] 更改为[HttpPost]
  • @Kris 这似乎至少可以解决获取请求。多谢,伙计。让它成为一个答案,我会接受它:)

标签: javascript c# asp.net ajax


【解决方案1】:

您是否刚刚尝试将“/Home/GetCredentials”作为 URL 访问?同样如上所述,更改为 GET 方法,删除 contentType 并将 dataType 更改为“文本”,因为您的控制器没有返回 JSON。

【讨论】:

  • 其实我试过他的解决方案,没有任何效果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2018-09-07
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多