【问题标题】:Why am I getting 415 trying to post a string?为什么我在尝试发布字符串时收到 415?
【发布时间】:2021-01-09 17:56:33
【问题描述】:

我想在注册时将电子邮件(字符串)从 aspnet/identity 发送到我的 dbcontext。控制台输出

加载资源失败。服务器响应状态为 415 () :5001/api/UserEntities/insertEmail:1

当我点击斜体部分时,我得到:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"不支持的媒体类型","status":415,"traceId": "00-30216fe89ca6b54e8fa1121b1954ad81-0a607d94a5b71142-00"}

RegisterConfirmation.cshtml

    var data = {
            email: $('#email').val()
        };
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: '../../api/UserEntities/insertEmail',
            data: data,
            success: function () {
                alert($('#email').val()); //this shows the email correctly in the popup
            }
        });
    });

UserEntitiesController.cs


    [Route("insertEmail")]
    public void Insert([FromBody] string email)
    {
        _uecontext.Users.Add(new DinderDL.Models.UserEntity
        {
            Email = email
        });
        _uecontext.SaveChanges();
    }

我也试过这个,结果是一样的:


    $(document).ready(function () {
        $.post('../../api/UserEntities/insertEmail', {
            email: $('#email').val();
        }).then(alert('hello'));
    });

除非我得到:

POST https://localhost:5001/api/UserEntities/insertEmail 415
send @ jquery.min.js:2
ajax @ jquery.min.js:2
S.<computed> @ jquery.min.js:2
(anonymous) @ RegisterConfirmation?email=baba@gmail.com&returnUrl=%2F:71
e @ jquery.min.js:2
t @ jquery.min.js:2
setTimeout (async)
(anonymous) @ jquery.min.js:2
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
fire @ jquery.min.js:2
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
ready @ jquery.min.js:2
B @ jquery.min.js:2

【问题讨论】:

  • 尝试设置“Content-Type: application/x-www-form-urlencoded”或查看这个答案:link
  • 我得到了同样的结果:/

标签: jquery entity-framework asp.net-core razor


【解决方案1】:

您的 api 端点接受具有有效请求正文的请求(由在输入字符串 email 上装饰的 [FromBody] 确定),但您的请求使用默认的 contentTypeapplication/x-www-form-urlencoded(由 $.ajax)发布。这会导致发送一个空的请求正文。

所以您有 2 个选项,要么删除 [FromBody],要么发布内容类型为 application/json 的 ajax 请求。使用该内容类型,传递给data 选项的整个字符串将通过请求正文发送。服务器端代码将使用 json 序列化格式化程序(输入格式化程序)解析该请求正文,因为 content-type 标头值为 application/json

这是您遵循第二个选项(发布 json 请求)的方式:

$.ajax({
        type: "POST",
        url: '../../api/UserEntities/insertEmail',
        contentType: 'application/json',
        data: data.email,
        success: function () {
           //...
        }
    });

注意:上面的代码我们不使用JSON.stringify,因为它是不必要的。您的服务器端模型只是一个string。如果使用JSON.stringify,您需要更新您的模型以使用这样的类:

//just an example to help you understand
public class DataModel {
    [JsonProperty("email")]
    public string Email {get;set;}
}
//update your Insert method to this
public void Insert([FromBody] DataModel data)
{
    //accessing data.Email
}
//then you can use JSON.stringify to post the json of your email object
$.ajax({
        type: "POST",
        url: '../../api/UserEntities/insertEmail',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function () {
           //...
        }
    });

参考资料:

FromBodyAttribute

Input formatters

【讨论】:

  • 好的,所以尝试两者(不确定什么算作服务器端代码,我的控制器应该有一个 json 序列化程序吗?)删除了 415,但我的数据库表中出现了空值,并且我控制器中的Console.WriteLine(email) 显示为空。
  • @SamBa 总是支持默认的 json 序列化程序。它应该很好地解析发布的值。您是否尝试过调试以查看是否获得了 email 的值?在Insert 方法的最开始处设置一个断点。如果你看到它,它就会起作用。由于您的保存逻辑,下一个代码可能会导致另一个问题,...(但不应在同一个问题中提出)。
  • @SamBa 看到我的更新,因为你的email 只是一个纯字符串,而不是一个复杂的模型。
  • 天哪,它有效,非常感谢。我现在脑子都炸了,我一会儿回来试着了解如何正确使用它
  • 不客气。我的回答很好地解释了它,只需仔细阅读它,它也有参考链接。这就是 asp.net 核心中所谓的model binding
【解决方案2】:

您只需要更改您的代码:

var data = {
            email: $('#email').val()
           };

    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url:'../../api/UserEntities/insertEmail',
            contentType: 'application/json',
            data:  JSON.stringify(data),
            success: function (result) {
               console.log(result);
            }
        });
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多