MVC Post 总是请求 returns IIS 错误 500 但与邮递员一起工作

MVC Post request always returns IIS error 500 but works with postman

我正在尝试向 IIS 中托管的 webapi 应用程序发送 post 请求。我总是收到 post 请求的错误 500,但获取请求工作正常。下面是我的代码

型号:

  public class LineModel 
  {
    [Key]
    public string ID { get; set; }

    public string No { get; set; }

    public string Name { get; set; }

    public string Title { get; set; }

    public string Code1 { get; set; }

    public string Code2 { get; set; }

    public DateTime Date { get; set; }

    public string Type { get; set; }

    public string Remarks { get; set; }

    public string Status { get; set; }
    
    public List<SubLine> SubLines { get; set; }
 }

Ajax 显示表单的代码:

$(function () {
  $(".surveyType").click(function () {
    var surveyType = $(this).attr("data-bind");
    $.ajax({
        url: "/Aella/Create/",
        data: { "surveyCode": surveyType },
        success: function (data) {
            console.log(data);
            $('#Question').html(data);
            };
        }
    });
});

Ajax 调用 post 请求:

$('body').on('click','#submit-request', function () {
    var formData = $("#create-request").serialize();
    console.log(formData);
    $.ajax({
        url: "/Aella/Create/",
        data: formData,
        type: "POST",
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        success: function (data) 
        {
            console.log(data);
        }
    });
});

获取请求:

    [HttpGet]
    public ActionResult Create(string surveyCode)
    {           
        questions = GetSurveyQuestions(surveyCode);           
        LineModel model = new LineModel
        {
            SubLines = questions.Select(a => new SubLine()
            {
                Question = a.questionField,
                Code = a.codeField,
                Type = a.question_TypeField.ToString(),
                Survey_Type = a.survey_TypeField,
                Response = "",
                Remark = ""
            }).ToList(),
            Type = surveyCode,
            Date = DateTime.Now
        };
        
        return View(model);
    }

Post方法:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(LineModel lineModel)
{           
   if(ModelState.IsValid)
   {
      lineModel.Status = "Open";
      foreach(var item in lineModel.SubLines)
      {
        if(item.Type == "Remark")
        {
            item.Remark = item.Response;
            item.Response = "";
        } 
      }
      HttpClient client = new HttpClient
      {
        BaseAddress = new Uri(ConfigurationManager.AppSettings["lineModelLink"].ToString())
      };
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      jsonContent = JsonConvert.SerializeObject(lineModel);
      contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");
      contentString.Headers.ContentType = new MediaTypeHeaderValue("application/json");
      HttpResponseMessage response = new HttpResponseMessage();
   
      try
      {
        response = await client.PostAsync(ConfigurationManager.AppSettings["lineModelLink"].ToString(), contentString);   
      }
      catch(HttpRequestException ex)
      {
        ErrorController.LogError(ex);
        ViewBag.Response = JsonConvert.DeserializeObject(responseStr);
        if (lineModel.lineModelLines.Count > 0)
        {
            ViewBag.IsQuestionAvailable = true;
        }
        return View(lineModel);
      }
      [...]
    }
   [...]
}

Post人工请求:

    {
    "No":"",
    "Name":"",
    "Title":"",
    "Code1":"",
    "Code2":"",
    "Date":"2021-10-25T00:00:00",
    "Type":"SEC",
    "Remarks":"",
    "Status":"Open",
    "SubLines":
    [
        {
            "Code":"01",
            "Question":"How did you learn about the job opening? ",
            "Type":"Defined",
            "Survey_Type":"SEC",
            "Response":"05",
            "Remark":""
        },
        {
            "Code":"02",
            "Question":"The job description/requirements were clear and understandable",
            "Type":"1-4",
            "Survey_Type":"SEC",
            "Response":"04",
            "Remark":""
        },
        {
            "Code":"03",
            "Question":"It was easy and convenient applying for the position",
            "Type":"1-4",
            "Survey_Type":"SEC",
            "Response":"04",
            "Remark":""
        },
        {
            "Code":"04",
            "Question":"The recruiter was professional.",
            "Type":"1-4",
            "Survey_Type":"SEC",
            "Response":"02",
            "Remark":""
        }
    ]
}

表单(主视图):

@using (Html.BeginForm("Create", "Aella", FormMethod.Post, new { id = "create-request", enctype = "multipart/form-data" }))
        {
            @Html.AntiForgeryToken()
            <div class="">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div id="survey-header" class="survey-shape-border">
                    
                    @Html.EditorFor(model => model.No, new { htmlAttributes = new { @class = "input100" } })
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "input100" } })
                    @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "input100" } })
                                        
                    @Html.EditorFor(model => model.Code1, new { htmlAttributes = new { @class = "input100" } })
                    @Html.EditorFor(model => model.Code2, new { htmlAttributes = new { @class = "input100" } })         
                        
                    @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "input100", @readonly = "readonly" } })
                        
                        @Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "input100", @readonly = "readonly" } })
                        @Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "input100" } })
                                
                        @Html.EditorFor(model => model.Status, new { htmlAttributes = new { @class = "input100" } })
                                
                </div>
                    @foreach (var line in Model.SubLines)
                    {
                        @Html.Partial("_Lines", line)
                    }

                <div class="display-none">
                    <button type="button" value="Create" class="btn-lg" id="submit-request">Submit Survey</button>
                </div>
            </div>
        }

局部视图:

@using HtmlHelpers.BeginCollectionItem;    
<div class="">
    @using (Html.BeginCollectionItem("SubLines"))
    {
        <div>
            @Html.HiddenFor(model => model.ID)
            @Html.HiddenFor(model => model.Type)
            @Html.HiddenFor(model => model.Type)
            @Html.HiddenFor(model => model.Question)    
            @Html.HiddenFor(m => m.Code)
        </div>
        
        if (Model.Type == "Defined")
        {
            <div class="userDefined_6 survey-line-response">
                <label> @Html.RadioButtonFor(model => model.Response, "01")<span>Job Board</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "02")<span>Careers Website</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "03")<span>Linkedin</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "04")<span>Friend/Colleague</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "05")<span>Recruiter</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "06")<span>Others(Please State)</span></label>
            </div>
        }
        if (Model.Type == "1-4")
        {
            <div class="userDefined_4 survey-line-response">

                <label> @Html.RadioButtonFor(model => model.Response, "01")<span>Strongly Disagree</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "02")<span>Disagree</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "03")<span>Agree</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "04")<span>Strongly Agree</span></label>
            </div>
        }
        if (Model.Type == "1-5")
        {
            <div class="userDefined_5 survey-line-response">

                <label> @Html.RadioButtonFor(model => model.Response, "01")<span>1</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "02")<span>2</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "03")<span>3</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "04")<span>4</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "05")<span>5</span></label>
            </div>
        }
        if (Model.Type == "1-15")
        {
            <div class="userDefined_10 survey-line-response">

                <label> @Html.RadioButtonFor(model => model.Response, "01")<span>1</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "02")<span>2</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "03")<span>3</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "04")<span>4</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "05") <span> 5 </span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "06")<span>6</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "07")<span>7</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "08")<span>8</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "09")<span>9</span></label>
                <label> @Html.RadioButtonFor(model => model.Response, "10")<span>10</span></label>
            </div>
        }
        if (Model.Type == "Open")
        {
            <div class="userDefined_Narration survey-line-response">
                @Html.EditorFor(model => model.Response, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Response, "", new { @class = "text-danger" })
            </div>
        }
    }
</div>

来自服务器的响应:

    HTTP/1.1 500 Internal Server Error
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/8.5
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Date: Wed, 03 Nov 2021 12:15:35 GMT
    Content-Length: 36

    {"Message":"An error has occurred."}

为此花了好几个小时。我将非常感谢帮助,因为我缺少答案。

你的postajax请求有一个包

    url: "/Survey/CreateSurvey/",

但您的操作是创建。您必须调整操作名称。

而且 Get 操作似乎应该在同一个控制器中,但它也有一个奇怪的 url

   url: "/Aella/Create/",

修复这些错误后,尝试调试应用程序的其他部分,一次一个步骤。因为我可以在您的局部视图中看到很多我以前从未见过的 html 助手,所以我不确定它们是否生成了可以提交的正确 mvc html。所以恕我直言,首先评论部分观点并尝试使工作成为主要观点。在此之后,您可以继续逐行添加部分视图。

关于代码的一切都很好,我观察到服务器上的证书已过期,因此出现错误。谢谢大家