【问题标题】:Returned 404 Not Found when request user email [ASP.NET Web API]请求用户电子邮件时返回 404 Not Found [ASP.NET Web API]
【发布时间】:2019-09-05 20:52:37
【问题描述】:

我正在尝试通过使用 JQuery 在输入框中写入电子邮件(以选择消息收件人)从 ASP.NET Web API 获取用户电子邮件,但返回值为 null。在我的代码中传递过程是否有任何问题?

网络 API:

[AllowAnonymous]
        [HttpGet]
        [Route("get-reciver-email")]
        public ApplicationUser GetReciverEmailId([FromUri] string email)
        {
            return _userManager.FindByEmail(email);

        }

客户端“JQuery”:

$('#toEmail').keyup(function () {
                $.ajax({
                    url: '/api/Account/get-reciver-email/' + $("#toEmail").val(),
                    method: 'GET',
                    success: function (response) {
                        console.log(response);
                    },
                    // Display errors if any in the Bootstrap alert <div>
                    error: function (jqXHR) {
                        $('#divErrorText').text(jqXHR.responseText);
                        $('#divError').show('fade');
                    }
                });
            });

我希望根据传递的 HTML 格式的电子邮件返回用户信息。

【问题讨论】:

  • 尝试在 ajax 请求中指定绝对 URL(或检查网络选项卡以确保发出的请求正确)。如果这不起作用,请在此处发布您的路线注册。
  • 但是,documentation 状态 [FromUri] 用于复杂类型,因此我将删除它并将电子邮件添加为查询字符串 '/api/Account/get-reciver-email?email=' + $("#toEmail").val()
  • 应用程序中的所有路由都正常工作,除了这个。我怀疑问题出在客户端的传递过程中,这是网络和控制台选项卡:i.imgur.com/shcyc7S.png
  • 好的,我试试。
  • 我删除了 [FromUri] 并添加了 ?email=' + $("#toEmail").val()。现在发生了异常! :i.imgur.com/v5OcPjz.png

标签: javascript c# jquery asp.net-web-api


【解决方案1】:

解决了。

我删除了 [FromUri] 并使用了查询字符串(@Mihai 的 THX),我还将 API 函数修改为以下内容:

[AllowAnonymous]
[HttpGet]
[Route("get-reciver-email")]
public string GetReciverEmailId(string email)
{
    return   db.Users.Where(x => x.Email == email).Select(x => x.Id).Single();

}

客户端代码:

$('#toEmail').keyup(function () {
                $.ajax({
                    url: '/api/Account/get-reciver-email/?email=' + $("#toEmail").val(),
                    method: 'GET',
                    success: function (response) {
                        console.log(response);
                    },
                    // Display errors if any in the Bootstrap alert <div>
                    error: function (jqXHR) {
                        $('#divErrorText').text(jqXHR.responseText);
                        $('#divError').show('fade');
                    }
                });
            });

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2021-11-04
    • 1970-01-01
    • 2016-01-01
    • 2021-02-07
    相关资源
    最近更新 更多