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

时间:2019-06-30 21:14:42

标签: c# sql-server asp.net-mvc entity-framework .net-core

场景

我正在建立一个博客,并正在配置一个页面以将编辑后的评论发布到MsSql服务器。

问题

在我提交提交表单POST之后,通过我的视图,应该通过此表单捕获并返回的属性值都全部返回为“ NULL”!由于我的数据模型中存在NULL值,最终将导致异常错误。在浏览完整个应用程序并使用Fiddler之后,我无法诊断问题。

快速直观示例

  

提交POST(在运行时)并且我的应用程序到达博客的 Home Controller 后,显示并可用的内容。

注意:如您所见,Home Controller在运行时会捕获每个输入的值。但是,此数据不会传输到 EditComment 方法发布的POST

过程

使用我的模型的属性值填充输入控件,然后提交:

  

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>

我的AppDbContext已初始化

  

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; }
    }
}

我的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;
        }
    }

一旦没有任何填充,将启动Home Controller,并调用以下函数:

  

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);
    }

此时,从POST填充的 comment 参数变量仅包含NULL值,并显示为:

调查与分析

VisualStudio

  • 本地变量检查器
    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}

此过程可以在设置为实现此完全相同功能的其他过程上按预期工作,只是在不同的表上!?

例如,这是Fiddler通过几乎相同的POST过程在成功的POST上捕获的内容:

提琴手检查器

  • 原始(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

提琴手检查器

  • 原始(编辑注释失败)
    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

注意:所有内容看上去都一样(应该出现的地方),但POST URL不一致。每次对此进行故障排除时,我都会输入第一个条目,对其进行编辑,然后提交。每次执行此操作时(在其他四个可以正常工作的过程中),它都会迭代到下一个条目;如上所示。

示例:    A)当有 20个项目条目

时,编辑并提交项目1
POST https://localhost:44390/Home/EditProject/21 <=== discrepancy

B)有 20条评论时,编辑并提交评论1

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

Chrome(网络标题)

  

成功(项目)

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
---------------------------------------------------------------------------------------------------
  

失败(评论)

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(流量分析)

  

成功(编辑项目)

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
  

失败(编辑评论)

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

其他信息

项目配置

  

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>

数据库

  

[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,
    )

插入查询

  

CommentsInsertQuery.sql

     

这将完全与(通常)通过上述表格提交的数据相同;效果很好。

    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');

最终思想

我担心这个问题可能发生在实体框架内的某个地方,我无法进行故障排除。如果我有一个真诚的起点,可以确定.Net框架捕获浏览器数据的确切点,那么我也许可以更好地确定关键问题。

类似的帖子:

  

ASP.NET CORE Web API: Model value is null when doing HTTP Post requests with null Guid

     
    

此问题与替代问题非常相似,但是,故障排除似乎更少,并且有关此问题的信息也更少。此外,在这个问题上没有多大兴趣,也没有提供解决方案。

  

预先感谢,并欢呼

2 个答案:

答案 0 :(得分:0)

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

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

在ASP.Net中,您应该使用FromUri。它告诉解析器在URL中查找对象。 您还可以使用FromBody告诉解析器在请求正文中查找对象。

答案 1 :(得分:0)

Jerry索具解决方案

我能够管理一种解决方法,尽管我仍不确定该错误发生的“原因”。

简介

感觉回发数据是在应用程序Graphic中捕获的,但是,它没有填充EditComments方法的参数值,我只是手动填充数据。

解决方案

在我的Home Controller中包含了Microsoft.AspNetCore.Http库,并修改了以下的回发后的method

  

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);
    }

  

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);
    }

...并且一切正常。

附加说明

这些值很容易检索,以防其他人遇到类似问题。只需将请求表单数据转换为List(如上所述),然后通过输出控制台将这些结果打印出来即可。

示例:

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

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