简体   繁体   English

ASP.NET MVC核心Web POST请求使用NULL值填充数据模型

[英]ASP.NET MVC Core Web POST Request populating Data Model with NULL values

Scenario 情境

I'm setting up a blog and am configuring a page to POST edited comments to an MsSql server. 我正在建立一个博客,并正在配置一个页面以将编辑后的评论发布到MsSql服务器。

Issue 问题

After I submit submit a form POST, via my view, the property values that are supposed to be captured and returned via this form, are all returned as "NULL"!? 在我提交提交表单POST之后,通过我的视图,应该通过此表单捕获并返回的属性值都全部返回为“ NULL”! This eventually causes an exception error due to there being NULL values present within my data model. 由于我的数据模型中存在NULL值,最终将导致异常错误。 After stepping through my entire application, and using Fiddler, I am unable to diagnose the issue. 在浏览完整个应用程序并使用Fiddler之后,我无法诊断问题。

Quick Visual Example 快速视觉示例

After a POST has been submitted (during run-time) and my application has reached the Home Controller of my blog, this is what's shown and available. 在提交POST (在运行时)并且我的应用程序到达博客的Home Controller之后,这就是显示和可用的内容。

Note: as you can see, each input's value is captured by the Home Controller during run-time. 注意:如您所见,每个输入的值在运行时由Home Controller捕获。 However, this data is not transferred to the EditComment method post POST . 但是,此数据不会在POST传输到EditComment方法。

Process 处理

Input controls are populated with property values for my model, then submitted: 输入控件使用我的模型的属性值填充,然后提交:

EditComments.cs EditComments.cs

    @model MpComment

    ... HTML Content ...

    <form asp-controller="Home" asp-action="EditComment" method="post" class="text-danger input-form">
        <div asp-validation-summary="ModelOnly"></div>
        <div class="form-group">
            <label asp-for="<Model.Property>" class="control-label"></label>
            <input asp-for="<Model.Property>" class="form-control" />
            <span asp-validation-for="<Model.Property>" class="text-danger"></span>
        </div>

        ... ASP Form Input Elements...

        <div class="form-group input-submit">
            <input type="submit" value="Submit" class="btn material-button" />
        </div>
    </form>

My AppDbContext is initialized 我的AppDbContext已初始化

AppDbContext.cs AppDbContext.cs

namespace Portfolio.Data
{
    public class AppDbContext : IdentityDbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

        public virtual DbSet<MpPost> MpPost { get; set; }
        public virtual DbSet<MpComment> MpComment { get; set; }
        public virtual DbSet<MpGuest> MpGuest { get; set; }
        public virtual DbSet<MpLogin> MpLogin { get; set; }
        public virtual DbSet<MpProject> MpProject { get; set; }
    }
}

My MpComments model begins to appear to move through and set each properties value, however, the data that populates each property is NULL. 我的MpComments模型开始看起来像遍历并设置每个属性值,但是,填充每个属性的数据为NULL。

    using System;
    using System.ComponentModel.DataAnnotations;

    namespace Portfolio.Models
    {
        public partial class MpComment
        {
            public int Id { get; set; }
            public int Mp_Post_Id { get; set; }
            public int Mp_Guest_Id { get; set; }
            public string Comment { get; set; }
            public int? Karma { get; set; }
            public int? Approved { get; set; }
            public string Ip { get; set; }
            public string Agent { get; set; }
            public DateTime? Create { get; set; } = DateTime.Now;
            public DateTime? Update { get; set; } = DateTime.Now;
        }
    }

Once nothing gets populated, the Home Controller is initiated, and the following function is called: 一旦没有填充任何东西,就启动家庭控制器,并调用以下函数:

HomeController.cs HomeController.cs

    [HttpPost]
    public async Task<IActionResult> EditComment(MpComment comment)
    {
        comment.Id = 0;

        _repo.AddComment(comment);

        if (await _repo.SaveChangesAsync())
            return RedirectToAction("ViewComments");
        else
            return View(comment);
    }

It's at this point where the comment parameter variable populated from the POST contains only NULL values, and appears like so: 此时,从POST填充的comment参数变量仅包含NULL值,如下所示:

Investigation & Analysis 调查与分析

VisualStudio 视觉工作室

  • Local Variable Inspector 局部变量检查器
    Agent        null
    Approved     null
    Comment      null
    Create       {6/30/2019 1:04:29 PM}
    Id           0
    Ip           null
    Karma        null
    Mp_Guest_Id  0
    Mp_Post_Id   0
    Update       {6/30/2019 1:04:29 PM}

This procedure works as expected on other procedures set to accomplish this exact same feature, just on a different table!? 此过程可以在其他设置成完全相同的功能的过程上按预期工作,只是在不同的表上!

For example, here's what Fiddler captured on a successful POST, from an almost identical POST'ing procedure: 例如,这是Fiddler通过几乎相同的POST过程在成功的POST上捕获的内容:

Fiddler Inspector 提琴手督察

  • Raw (Success for EditProject) 原始(EditProject的成功)
    POST https://localhost:44390/Home/EditProject/21 HTTP/1.1
    Host: localhost:44390
    Connection: keep-alive
    Content-Length: 555
    Cache-Control: max-age=0
    Origin: https://localhost:44390
    Upgrade-Insecure-Requests: 1
    Content-Type: application/x-www-form-urlencoded
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
    Referer: https://localhost:44390/Home/EditProject/21
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.9,mt;q=0.8
    Cookie: .AspNetCore.Antiforgery.x5eNnYCJ5UA=CfDJ8OfA6sTjcU1PuqxxzGM-oMrl1aZfFqqMphsPHMioPYeJIj8tRRSXB1N9Pm7JhspsKDyUKawAVJYkSlP56myEU4qcRohQ1axrDWFXPVvZjlNZqiRZAZVOMcZ3wupV12M_z289E7MaUrZ1nbOzH34eiH0; .AspNetCore.Identity.Application=CfDJ8OfA6sTjcU1PuqxxzGM-oMp2YqORrHzf5IL0rLJ8jvAP-RYvHIXeH63EfD3-TugdZGBP9nf_lHhAn71ACsIQZe_cJ1x7u3FBh25uhlXZIJX9yk7ZdH_GuwfYEe-Zaa1CSAD2f2g8U7syt8jvxy18c-qCN9Yq2zLQpBeOlzftudcaMKKrsA-UGO8BOHLPTk1TYe1QMosDGaFDLXY0POqCpluxiiA0qsA0i9iQeAP6HL7ZC8lLjf76Lf_E5usVyakwa9X3ELDJQeaEFFa5Vi_5063xCHhm3NRREE5loUCff1rKmaOKvvOR-Fnf-QtYLG-MGthgVAGah4cdXjD0jsKFBM0Ny-Yt8uRddQ26w_8AUJqhRo9jOAXEuzyhYwPRfKQKykgpy-4lVIZXc2QR25EWxq9H6zh5GGCTIitxISDcpoHf0mUqzT9aJKo_LwB6cibzbDwBmVsTc6Yn6cQA0MMoBVa6E6hKuvQoNerU7psX5z2D2k8tB8mZVlJQ3medeMwHQonOSBh99OxOrBO5K6iedlpPqSNco8r7PbNcHCdhLKehtoyJkE3tzmrv_EOTAS7ldXNhhPHqNp_RmuAdGWlsJ-a-bN5itj1hv_o7RCxl8t49XB9oddsg4iOvR-BUZOLuxJKfQ90PAH4S9BvblwLKoXx3Gt3We5WeG8Ga6rAXHQhd

    Id=0&Title=Product+Engineer&Desc=nulla+neque+libero+convallis+eget+eleifend&Live_Url=bloglovin.com%2Feget%2Ftincidunt%2Feget.jpg&Github_Repo=sourceforge.net%2Fet%2Fultrices%2Fposuere%2Fcubilia.jpg&Bitbucket_Repo=creativecommons.org%2Fpede%2Flibero%2Fquis.html&Create=2011-07-11T00%3A00%3A00.000&Update=2019-06-20T00%3A00%3A00.000&__RequestVerificationToken=CfDJ8OfA6sTjcU1PuqxxzGM-oMqTHmlRblU70EY0Ou7tH2IifiXdJOCtMRepfMg-GhKz-j4at6h9BOzJTNjHIROMjDpUiOqxvDeGWcja8K-uGkYrW8DX58j9mIFlwKML9tLVtvusmGmPekVMPxYqRkKdcyLGb6qpav3upDLAvfxLblbs9RynCyG4bDTAAZ4jzxc-ww

Fiddler Inspector 提琴手督察

  • Raw (Failure for EditComments) 原始(EditComments失败)
    POST https://localhost:44390/Home/EditComment/1 HTTP/1.1
    Host: localhost:44390
    Connection: keep-alive
    Content-Length: 606
    Cache-Control: max-age=0
    Origin: https://localhost:44390
    Upgrade-Insecure-Requests: 1
    Content-Type: application/x-www-form-urlencoded
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
    Referer: https://localhost:44390/Home/EditComment/1
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.9,mt;q=0.8
    Cookie: .AspNetCore.Antiforgery.x5eNnYCJ5UA=CfDJ8OfA6sTjcU1PuqxxzGM-oMrl1aZfFqqMphsPHMioPYeJIj8tRRSXB1N9Pm7JhspsKDyUKawAVJYkSlP56myEU4qcRohQ1axrDWFXPVvZjlNZqiRZAZVOMcZ3wupV12M_z289E7MaUrZ1nbOzH34eiH0; .AspNetCore.Identity.Application=CfDJ8OfA6sTjcU1PuqxxzGM-oMp2YqORrHzf5IL0rLJ8jvAP-RYvHIXeH63EfD3-TugdZGBP9nf_lHhAn71ACsIQZe_cJ1x7u3FBh25uhlXZIJX9yk7ZdH_GuwfYEe-Zaa1CSAD2f2g8U7syt8jvxy18c-qCN9Yq2zLQpBeOlzftudcaMKKrsA-UGO8BOHLPTk1TYe1QMosDGaFDLXY0POqCpluxiiA0qsA0i9iQeAP6HL7ZC8lLjf76Lf_E5usVyakwa9X3ELDJQeaEFFa5Vi_5063xCHhm3NRREE5loUCff1rKmaOKvvOR-Fnf-QtYLG-MGthgVAGah4cdXjD0jsKFBM0Ny-Yt8uRddQ26w_8AUJqhRo9jOAXEuzyhYwPRfKQKykgpy-4lVIZXc2QR25EWxq9H6zh5GGCTIitxISDcpoHf0mUqzT9aJKo_LwB6cibzbDwBmVsTc6Yn6cQA0MMoBVa6E6hKuvQoNerU7psX5z2D2k8tB8mZVlJQ3medeMwHQonOSBh99OxOrBO5K6iedlpPqSNco8r7PbNcHCdhLKehtoyJkE3tzmrv_EOTAS7ldXNhhPHqNp_RmuAdGWlsJ-a-bN5itj1hv_o7RCxl8t49XB9oddsg4iOvR-BUZOLuxJKfQ90PAH4S9BvblwLKoXx3Gt3We5WeG8Ga6rAXHQhd

    Mp_Post_Id=1&Mp_Guest_Id=1&Comment=lorem+quisque+ut+erat+curabitur+gravida+nisi+at+nibh+in+hac+habitasse+platea+dictumst+aliquam&Karma=1&Approved=1&Ip=21.99.31.96&Agent=Mozilla%2F5.0+%28Macintosh%3B+U%3B+Intel+Mac+OS+X+10_7%3B+en-us%29+AppleWebKit%2F533.4+%28KHTML%2C+like+Gecko%29+Version%2F4.1+Safari%2F533.4&Create=2018-07-17T00%3A00%3A00.000&Update=2012-06-01T00%3A00%3A00.000&__RequestVerificationToken=CfDJ8OfA6sTjcU1PuqxxzGM-oMquggjJDBhMvQwfCKwHRJS9tJeBi-4bT19jJVjuUjZgYE1LD4BvCF2LBJlQ45u3d9sEGmm-l9EAhbXaA2TwuNjW4xhYpVXl4Z0YE_YBEvbuSzodxjP8v1GoYAXYfs5yl3L39SK0gp1YKkkwujMhdExO17v3n-b_y4IhhZJ3SanIZw

Note: Everything appears identical (where it should), except there's a discrepancy with the POST URL. 注意:除POST URL有所不同外,其他所有内容(应该出现的地方)都相同。 Each time I troubleshoot this, I take the 1st entry, edit it, and then submit it. 每次对此进行故障排除时,我都会输入第一个条目,对其进行编辑,然后提交。 Each time I do this (on the four other procedures where this works fine), it iterates to the next entry; 每次执行此操作时(在其他四个可以正常工作的过程中),它都会迭代到下一个条目; as seen above. 如上所示。

Example: A) Edit & Submit Project 1 when there's 20 Project entries : 示例: A)当有20个项目条目时,编辑并提交项目1

POST https://localhost:44390/Home/EditProject/21 <=== discrepancy

B) Edit & Submit Comment 1 when there's 20 Comment entries : B)当有20条评论条目时,编辑并提交评论1

POST https://localhost:44390/Home/EditComment/1 <=== discrepancy

Chrome (Network Headers) Chrome(网络标题)

Success (Project) 成功 (项目)

General:
    Request URL: https://localhost:44390/Home/EditProject/66
    Request Method: POST
    Status Code: 302
    Remote Address: [::1]:44390
    Referrer Policy: no-referrer-when-downgrade
---------------------------------------------------------------------------------------------------
Response Headers:
    content-length: 0
    date: Mon, 01 Jul 2019 00:04:16 GMT
    location: /Home/ViewProjects
    server: Kestrel
    status: 302
    x-powered-by: ASP.NET
    x-sourcefiles: =?UTF-8?B?QzpcV29ya3NwYWNlXHd3d1xhc3BcUG9ydGZvbGlvXFBvcnRmb2xpb1xIb21lXEVkaXRQcm9qZWN0XDY2?=
---------------------------------------------------------------------------------------------------
Request Headers:
    :authority: localhost:44390
    :method: POST
    :path: /Home/EditProject/66
    :scheme: https
    accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
    accept-encoding: gzip, deflate, br
    accept-language: en-US,en;q=0.9,mt;q=0.8
    cache-control: max-age=0
    content-length: 1200
    content-type: application/x-www-form-urlencoded
    cookie: .AspNetCore.Antiforgery.x5eNnYCJ5UA=CfDJ8OfA6sTjcU1PuqxxzGM-oMrl1aZfFqqMphsPHMioPYeJIj8tRRSXB1N9Pm7JhspsKDyUKawAVJYkSlP56myEU4qcRohQ1axrDWFXPVvZjlNZqiRZAZVOMcZ3wupV12M_z289E7MaUrZ1nbOzH34eiH0; .AspNetCore.Identity.Application=CfDJ8OfA6sTjcU1PuqxxzGM-oMpTJYFjUyUy3eLO3fbnX9V4SSq14P_h_AlTAyZs-9LrMW9QOzTP46d8CJetHqzamw-ulm6IbjGyC_hElFiwtJRbKAV3GuVlGQeNfbhcJ7M81EH4bqnbi-NBwP4nmlXROTG3DvMYdHqC1-eqT53ip4mnHpdLDLKlwX80Lk8uWPpiyD5L_RFiMGl5i0vOUz19bbn-mSC3IVbuGz8LeDePfKDmU-3b8_sNiZJpBpx4p6jORrds69LkpkdZX2NUWzyevM4TWw8irVRRBY0PAFKkkZEfQy52kPFfHLZgcZ2JMFo2iQ0DqRcq7nqwnU1JRbNTHEQ56WOsStWn7IGfBqA43B5QdLn-yWTiP5AIalG3kv_o-6VZTmyfu6QbBCbwD_7gpjewoB8IiYn86WaTVbvkryGBJZMjSEq5M2H1m365zI392lNZVzwDADwF04s4zYmHx8snkk9Z3NUAjvzDJo9b1IJNNIKnPmERysOR73W_hAfZdpVN0Ltx2fT7-13g4ow-2Xizi_t2b4SQcX6tC_tlju224eh0KkKNxOJ3irBQRsWAT9iKe_aaE7usFUkZgfR9vuZnPO62qzuxUwROsX3-Tz4lSxSD2N4ajqpEpVMcS528hMO5lXQwMA2RpGBKpR2JJzsN1KdbYgPcB16Ad14VgJNJ
    origin: https://localhost:44390
    referer: https://localhost:44390/Home/EditProject/66
    upgrade-insecure-requests: 1
    user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
---------------------------------------------------------------------------------------------------
Form Data:
    Title: Product Engineer
    Desc: nulla neque libero convallis eget eleifend
    Content: sodales scelerisque mauris sit amet eros suspendisse accumsan tortor quis turpis sed ante vivamus tortor duis mattis egestas metus aenean fermentum donec ut mauris eget massa tempor convallis nulla neque libero convallis eget eleifend luctus ultricies eu nibh quisque id justo sit amet sapien dignissim vestibulum vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae nulla dapibus dolor vel est donec odio justo sollicitudin ut suscipit a feugiat et eros vestibulum ac est lacinia nisi venenatis tristique fusce congue diam id ornare
    Project_Image: http://dummyimage.com/193x141.jpg/ff4444/ffffff
    Live_Url: bloglovin.com/eget/tincidunt/eget.jpg
    Github_Repo: sourceforge.net/et/ultrices/posuere/cubilia.jpg
    Bitbucket_Repo: creativecommons.org/pede/libero/quis.html
    Create: 2011-07-11T00:00:00.000
    Update: 2019-06-20T00:00:00.000
    __RequestVerificationToken: CfDJ8OfA6sTjcU1PuqxxzGM-oMq4kGmbGOLj875J5O8hQlwLIYQR7YHYe58lgzEyN5Wat3viIjRuF80IPiwf_iRYUydAC0vfWv-q5jvLA_bAsdz7blAbvNoT4TxTYqZ5ONf5Q2bYqOyWlhdoN7ZduEaRc3dEBua_8F35F6mNuq0NFfLTDkvlCvO1da4dbhsWg49nsg
---------------------------------------------------------------------------------------------------

Failure (Comment) 失败 (评论)

General:
    Request URL: https://localhost:44390/Home/EditComment/20
    Request Method: POST
    Status Code: 500
    Remote Address: [::1]:44390
    Referrer Policy: no-referrer-when-downgrade
---------------------------------------------------------------------------------------------------
Response Headers:
    content-type: text/html; charset=utf-8
    date: Sun, 30 Jun 2019 23:40:23 GMT
    server: Kestrel
    status: 500
    x-powered-by: ASP.NET
    x-sourcefiles: =?UTF-8?B?QzpcV29ya3NwYWNlXHd3d1xhc3BcUG9ydGZvbGlvXFBvcnRmb2xpb1xIb21lXEVkaXRDb21tZW50XDIw?=
---------------------------------------------------------------------------------------------------
Request Headers:
    :authority: localhost:44390
    :method: POST
    :path: /Home/EditComment/20
    :scheme: https
    accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
    accept-encoding: gzip, deflate, br
    accept-language: en-US,en;q=0.9,mt;q=0.8
    cache-control: max-age=0
    content-length: 558
    content-type: application/x-www-form-urlencoded
    cookie: .AspNetCore.Antiforgery.x5eNnYCJ5UA=CfDJ8OfA6sTjcU1PuqxxzGM-oMrl1aZfFqqMphsPHMioPYeJIj8tRRSXB1N9Pm7JhspsKDyUKawAVJYkSlP56myEU4qcRohQ1axrDWFXPVvZjlNZqiRZAZVOMcZ3wupV12M_z289E7MaUrZ1nbOzH34eiH0; .AspNetCore.Identity.Application=CfDJ8OfA6sTjcU1PuqxxzGM-oMpTJYFjUyUy3eLO3fbnX9V4SSq14P_h_AlTAyZs-9LrMW9QOzTP46d8CJetHqzamw-ulm6IbjGyC_hElFiwtJRbKAV3GuVlGQeNfbhcJ7M81EH4bqnbi-NBwP4nmlXROTG3DvMYdHqC1-eqT53ip4mnHpdLDLKlwX80Lk8uWPpiyD5L_RFiMGl5i0vOUz19bbn-mSC3IVbuGz8LeDePfKDmU-3b8_sNiZJpBpx4p6jORrds69LkpkdZX2NUWzyevM4TWw8irVRRBY0PAFKkkZEfQy52kPFfHLZgcZ2JMFo2iQ0DqRcq7nqwnU1JRbNTHEQ56WOsStWn7IGfBqA43B5QdLn-yWTiP5AIalG3kv_o-6VZTmyfu6QbBCbwD_7gpjewoB8IiYn86WaTVbvkryGBJZMjSEq5M2H1m365zI392lNZVzwDADwF04s4zYmHx8snkk9Z3NUAjvzDJo9b1IJNNIKnPmERysOR73W_hAfZdpVN0Ltx2fT7-13g4ow-2Xizi_t2b4SQcX6tC_tlju224eh0KkKNxOJ3irBQRsWAT9iKe_aaE7usFUkZgfR9vuZnPO62qzuxUwROsX3-Tz4lSxSD2N4ajqpEpVMcS528hMO5lXQwMA2RpGBKpR2JJzsN1KdbYgPcB16Ad14VgJNJ
    origin: https://localhost:44390
    referer: https://localhost:44390/Home/EditComment/20
    upgrade-insecure-requests: 1
    user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
---------------------------------------------------------------------------------------------------
Form Data:
    Mp_Post_Id: 20
    Mp_Guest_Id: 20
    Comment: etiam faucibus cursus urna ut tellus nulla ut erat id mauris vulputate elementum nullam varius nulla
    Karma: 6
    Approved: 0
    Ip: 142.146.130.50
    Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20120405 Firefox/14.0a1
    Create: 2010-10-21T00:00:00.000
    Update: 2009-10-07T00:00:00.000
    __RequestVerificationToken: CfDJ8OfA6sTjcU1PuqxxzGM-oMpEiWlpyDJHiDaw7Rz0PI6fyiscJ9aAahlk0J2Coz5R42uB-L3LvBS94t5QxvcBZ2PwMUI9McLlFR1rtds9yh89UZSzHpR-q_SvbM1g4KCUYDhvNht_bMaoy9NJvMTfOCR_TPW4CKTMnJCR8OEJYahY9CWXY_GozMl1MMkL3MFkFQ
---------------------------------------------------------------------------------------------------

Wireshark (Traffic Analysis) Wireshark(流量分析)

Success (Edit Project) 成功 (编辑项目)

POST /Home/EditProject/2 HTTP/1.1
Cache-Control: max-age=0
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,mt;q=0.8
Cookie: .AspNetCore.Antiforgery.x5eNnYCJ5UA=CfDJ8OfA6sTjcU1PuqxxzGM-oMrl1aZfFqqMphsPHMioPYeJIj8tRRSXB1N9Pm7JhspsKDyUKawAVJYkSlP56myEU4qcRohQ1axrDWFXPVvZjlNZqiRZAZVOMcZ3wupV12M_z289E7MaUrZ1nbOzH34eiH0; .AspNetCore.Identity.Application=CfDJ8OfA6sTjcU1PuqxxzGM-oMqPm6KX-2uhTXr62WeE6Jia-lF8RtuWQCtjegxTJyf6k-wmUcVdvsBAhEuLKWMN_ttD6dPUr-E8QGJPI_2fD0vYnbo6ADWRXWlMFHwloQ43bPBuSn0zPyp6rZvQLaYFXQXO2aO9Kk7UF64Nh4-kJenvCOcPYtv5JS5HneYXgXO_hM26wnG-3my6SaA4ApdBYndK4DbrdB4393HtLK1579yg7ON12bDIBH71pTMdK6UuIvAI1Bh3HbkUuCOtJzZ3ZqB_JQAutgRe6z6nFGcdPMcb0VbIUPa9USyg0oUJ9KxNPspX9y_dAt4GO18OrsFd-s8d-oWV7zDEMpQVBpLoaVk23xpiObUlVLfS-OQhfVgq3RAXAfkZOR7B7eusFkr3I_ZQRb__76x8dVRvHDy-gy_2ZU1xNJve0v-L38kRsVKoXpjCfc9HW9CaVZvoOH6YB1x-gwsGB_eJ8IJsMTnscrNhDloNlel42K7q8GlA-lTK9yXgiXqLm2VAYdpCf_b45ixMba0Cr7umLyMBzf7BEo3J5uNEAYvF7qN5DOlTSbuvwP33ZbBQJyu3uwnfi4JdzYHNDtlZJqlgUkVgmw_3snp3oJxizU50DFgTUyPjAuB71aEOEyVQRXbgZbJ_S-TzLddHc-hjZarUqKK6n5MBX-8_
Host: localhost:44390
Referer: https://localhost:44390/Home/EditProject/2
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
origin: https://localhost:44390
upgrade-insecure-requests: 1
MS-ASPNETCORE-TOKEN: 2a6aebc6-e154-4f02-9517-cae788a1069f
X-Forwarded-For: [::1]:60639
X-Forwarded-Proto: https
Content-Length: 710

Title=Senior+Quality+Engineer+IV&Desc=nascetur+ridiculus+mus+vivamus+vestibulum+sagittis+sapien+cum+sociis&Content=vivamus+tortor+duis+mattis+egestas+metus+aenean+fermentum+donec+ut+mauris+eget&Project_Image=http%3A%2F%2Fdummyimage.com%2F237x180.bmp%2F5fa2dd%2Fffffff&Live_Url=ihg.com%2Fgravida%2Fnisi%2Fat%2Fnibh.json&Github_Repo=paginegialle.it%2Fligula%2Fsuspendisse.xml&Bitbucket_Repo=harvard.edu%2Fcongue.aspx&Create=2018-09-07T00%3A00%3A00.000&Update=2013-05-17T00%3A00%3A00.000&__RequestVerificationToken=CfDJ8OfA6sTjcU1PuqxxzGM-oMqFkSNAgkReKvXjTW0EStR_OB4Zz6j90ZdieDNspaE86824rUys1Av2cI9mKtO15RaMnYSiz1_As63Ez0XWxX4N3zfL4vlgGfPQ43FMqqfcPBAG33xvi4G0naOTHEVTdGbiwkLrK2UVF2O01JzfVW3olYbxna45Pg10haFTI-s5QgHTTP/1.1 302 Found
Date: Mon, 01 Jul 2019 16:19:16 GMT
Server: Kestrel
Content-Length: 0
Location: /Home/ViewProjects

Failure (Edit Comments) 失败 (编辑评论)

POST /Home/EditComment/1 HTTP/1.1
Cache-Control: max-age=0
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,mt;q=0.8
Cookie: .AspNetCore.Antiforgery.x5eNnYCJ5UA=CfDJ8OfA6sTjcU1PuqxxzGM-oMrl1aZfFqqMphsPHMioPYeJIj8tRRSXB1N9Pm7JhspsKDyUKawAVJYkSlP56myEU4qcRohQ1axrDWFXPVvZjlNZqiRZAZVOMcZ3wupV12M_z289E7MaUrZ1nbOzH34eiH0; .AspNetCore.Identity.Application=CfDJ8OfA6sTjcU1PuqxxzGM-oMqsILl7uDq3qp0MgEGexCwq_b2cNi4376Wt5jxWgINpwDxVRedde5wkOvqycIGfKrQJM2uCVgFMc75i-3Ch_Sct3wFtj_o2wHjLt9OSgM1dieKWdY8BVsLWGHIsMkceMbh_GQz6xJsKrOixjijHUw88p990DPKm2dGJo-JLSHJpqxGNkQxlhPNPf-VsHEQmh27Mn2ah_NZj0NqIlxDuxfmeLQoV0W1s99zVg7URMUbSmGQsShrT1HxhcUjesLuGnyy90GdxmFyGf2-RKPl1zGdkQhaIgicmxQi-bR8otlu5E1uHPms-_HR3xZwT3koowKFYNM4NFHfPuQOwPgZooHCJeaYvweHuqiB5Oh98c6gRHalMSUqGApIICOfVY7mrr9uxt70PeB60PisyAfASCClKf0IsnJLh8flRZ5lr7cr4fhVXU9Jn-PS_09-iX262WvSgjWiPvfe6W_3QxhnPV1NBb0xVy7FCBNMeIIge0BftQzGMb0h_2xsCITwf9oAApXH-uTnC4E2FZI1nUzdfRVPCrj0kXsppeVr6q-65d9_cWgh2aDC4EYeCF4v__Yz9IZPoMKCvHF_rq_Vna4jLPLsobt4VcViYrSY66JmtO9IeoXpA3Ivd2P7ws4lcnJ9STgFV4oP3hmC4aRdA1BURRzz2
Host: localhost:44390
Referer: https://localhost:44390/Home/EditComment/1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
origin: https://localhost:44390
upgrade-insecure-requests: 1
MS-ASPNETCORE-TOKEN: 2a6aebc6-e154-4f02-9517-cae788a1069f
X-Forwarded-For: [::1]:61219
X-Forwarded-Proto: https
Content-Length: 606

Mp_Post_Id=1&Mp_Guest_Id=1&Comment=lorem+quisque+ut+erat+curabitur+gravida+nisi+at+nibh+in+hac+habitasse+platea+dictumst+aliquam&Karma=1&Approved=1&Ip=21.99.31.96&Agent=Mozilla%2F5.0+%28Macintosh%3B+U%3B+Intel+Mac+OS+X+10_7%3B+en-us%29+AppleWebKit%2F533.4+%28KHTML%2C+like+Gecko%29+Version%2F4.1+Safari%2F533.4&Create=2018-07-17T00%3A00%3A00.000&Update=2012-06-01T00%3A00%3A00.000&__RequestVerificationToken=CfDJ8OfA6sTjcU1PuqxxzGM-oMr9nzkkEn5p6n7jwRflZ1bmxhEOVzWiW7VXO1rmDYbHQR4CvYlmqH4LyuHMPDsQZWXE-gZ3eDU2LWqJd1uVnMKeJcbV0gne1gxSQdeg2Cd7wklVGIJAlC4PNr5hbqJmAGItiemNRukLVKMLVZ0E65dR-pVhxKy4SteMmvnDVMg5_QHTTP/1.1 500 Internal Server Error
Date: Mon, 01 Jul 2019 17:06:52 GMT
Content-Type: text/html; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked

Additional Information 附加信息

Project Configuration 项目配置

myProject.csproj myProject.csproj

    <Project Sdk="Microsoft.NET.Sdk.Web">

      <PropertyGroup>
        <TargetFramework>netcoreapp2.1</TargetFramework>
      </PropertyGroup>

      <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.2" />
        <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
        <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.9" />
        <PackageReference Include="MySql.data" Version="8.0.16" />
        <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.16" />
      </ItemGroup>

      <ItemGroup>
        <Folder Include="Migrations\" />
      </ItemGroup>

    </Project>

Database 数据库

[mpComment.sql] [mpComment.sql]

    CREATE TABLE [mpComment]
    (
        [id]            INT             NOT NULL        PRIMARY KEY,
        [mp_post_id]    INT             NOT NULL        FOREIGN KEY REFERENCES mpPost(id),
        [mp_guest_id]   INT             NOT NULL        FOREIGN KEY REFERENCES mpGuest(id),
        [comment]       NVARCHAR(500)   NOT NULL,
        [karma]         INT             NULL,
        [approved]      INT             NOT NULL,
        [ip]            NVARCHAR(100)   NULL,
        [agent]         NVARCHAR(255)   NULL,
        [create]        DATETIME        NULL,
        [update]        DATETIME        NULL,
    )

Insertion Query 插入查询

CommentsInsertQuery.sql CommentsInsertQuery.sql

This would be exactly the same data that would be (typically) submitted through the aforementioned form; 这将与(通常)通过上述表格提交的数据完全相同 which works fine. 效果很好。

    INSERT INTO [profileDb].[dbo].[mpComment] ([mp_post_id], [mp_guest_id], [comment], [karma], [approved], [ip], [agent], [create], [update])
    VALUES (1, 1, 'lorem quisque ut erat curabitur gravida nisi at nibh in hac habitasse platea dictumst aliquam', 1, 1, '21.99.31.96', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_7; en-us) AppleWebKit/533.4 (KHTML, like Gecko) Version/4.1 Safari/533.4', '07/17/2018', '06/01/2012');

Final Thoughts 最后的想法

I am concerned that this issue might be occurring somewhere within the Entity Framework, where I cannot troubleshoot. 我担心这个问题可能发生在实体框架中的某个地方,无法解决。 If I had a sincere point of origin where I can identify exact point where the data from my browser is captured by the .Net framework, I might be able to better identify the key issue. 如果我有一个真诚的起点,可以确定.Net框架捕获来自浏览器的数据的确切点,那么我也许可以更好地确定关键问题。

Similar Post: 类似帖子:

ASP.NET CORE Web API: Model value is null when doing HTTP Post requests with null Guid ASP.NET CORE Web API:执行带有空Guid的HTTP Post请求时,模型值为空

This question is very similar to an alternate question, however, there appears to be less troubleshooting, and a lot less information concerning the matter. 该问题与替代问题非常相似,但是,故障排除似乎更少,并且有关此问题的信息也更少。 In addition, there was not much love on this question, and no solutions provided. 另外,在这个问题上没有太多的热爱,也没有提供解决方案。

Thanks in advance, and cheers 预先感谢,并欢呼

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

public ValuesController : ApiController
{
     public HttpResponseMessage Post([FromUri] GeoPoint location) { ... }
}

In ASP.Net you should use FromUri. 在ASP.Net中,您应该使用FromUri。 It tells the parser to look for the object in the URL. 它告诉解析器在URL中查找对象。 You can also use FromBody to tell the parser to look for the objects in the request body. 您还可以使用FromBody告诉解析器在请求正文中查找对象。

Jerry Rigged Solution 杰里索具解决方案

I was able to manage a workaround, albeit, I'm still not certain "why" this error is occurring. 尽管我仍然不确定发生此错误的原因,但我仍然能够管理解决方法。

Synopsis 概要

Sense the post-back data was being captured within the application ( Graphic ) , however, it was not populating the parameter value of the EditComments method, I simply populated the data manually. 感觉到回发数据是在应用程序图形 )中捕获的,但是,它没有填充EditComments方法的参数值,我只是手动填充了数据。

Solution

Included the Microsoft.AspNetCore.Http library within my Home Controller, and modified the following post-back method from: 在我的Home Controller中包含了Microsoft.AspNetCore.Http库,并从以下method修改了以下回发method

HomeController.cs HomeController.cs

    [HttpPost]
    public async Task<IActionResult> EditComment(MpComment comment)
    {
        comment.Id = 0;

        _repo.AddComment(comment);

        if (await _repo.SaveChangesAsync())
            return RedirectToAction("ViewComments");
        else
            return View(comment);
    }

to

HomeController.cs HomeController.cs

    [HttpPost]
    public async Task<IActionResult> EditComment()
    {
        var form = Request.Form.ToList();

        var comment = new MpComment
        {
            Id          = 0,
            Mp_Post_Id  = Int32.Parse(form.Where(x => x.Key == "Mp_Post_Id").FirstOrDefault().Value),
            Mp_Guest_Id = Int32.Parse(form.Where(x => x.Key == "Mp_Guest_Id").FirstOrDefault().Value),
            Comment     = form.Where(x => x.Key == "Comment").FirstOrDefault().Value,
            Karma       = Int32.Parse(form.Where(x => x.Key == "Karma").FirstOrDefault().Value),
            Approved    = Int32.Parse(form.Where(x => x.Key == "Approved").FirstOrDefault().Value),
            Ip          = form.Where(x => x.Key == "Ip").FirstOrDefault().Value,
            Agent       = form.Where(x => x.Key == "Agent").FirstOrDefault().Value,
            Create      = Convert.ToDateTime(form.Where(x => x.Key == "Create").FirstOrDefault().Value),
            Update      = Convert.ToDateTime(form.Where(x => x.Key == "Update").FirstOrDefault().Value)
        };

        _repo.AddComment(comment);

        if (await _repo.SaveChangesAsync())
            return RedirectToAction("ViewComments");
        else
            return View(comment);
    }

...and everything works as expected. ...一切都按预期进行。

Additional note 附加说明

These values were easy enough to retrieve, in case anyone else has a similar issue. 这些值很容易检索,以防其他人遇到类似问题。 Simply convert the request form data into a List (as above) and print out those results via the output console. 只需将请求表单数据转换为List (如上),然后通过输出控制台将这些结果打印出来。

Example: 例:

    [HttpPost]
    public methodExpectingPostback()
    {
        var form = Request.Form.ToList();

        foreach (var item in form)
        {
            Debug.WriteLine($"{item.Key} : {item.Value}");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 model 和 null 值中的 Asp.net 核心 MVC DatatTypes - Asp.net core MVC DatatTypes in model and null values ASP.NET MVC核心POST请求不将JSON数据转换为Model - ASP.NET MVC core POST Request not converting JSON data to Model 使用 ASP.NET Core MVC 将带有文件的数据发布到 api (ASP.NET Core Web API) - Post data with files using ASP.NET Core MVC to api (ASP.NET Core Web API) ASP.NET MVC 5 Web API不接受来自MVC ASP.NET Core解决方案的POST上的视图模型 - ASP.NET MVC 5 Web API not accepting View Model on POST from MVC ASP.NET Core solution ASP.NET 核心 MVC 后 model 与 IEnumerable 或列表字段是 null - ASP.NET Core MVC post model with IEnumerable or List fields are null Asp.net core 3.1 mvc post request model 绑定简单类型 - Asp.net core 3.1 mvc post request model binding for simple types 使用ASP.NET Core MVC控制器将RestSharp POST请求连接到Web API - issue connecting RestSharp POST request to web API with ASP.NET Core MVC controller ASP.NET Core MVC model 参数值在 HttpPost 方法中变为 null - ASP.NET Core MVC model argument values becoming null in HttpPost method ASP.NET CORE MVC ViewModel 属性在发布时返回 Null - ASP.NET CORE MVC ViewModel property Return Null On Post ASP.NET Core MVC模型属性绑定为null - ASP.NET Core MVC model property binding is null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM