MVC Post 请求始终返回 IIS 错误 500,但适用于邮递员

Posted

技术标签:

【中文标题】MVC Post 请求始终返回 IIS 错误 500,但适用于邮递员【英文标题】:MVC Post request always returns IIS error 500 but works with postman 【发布时间】:2021-12-17 19:49:27 【问题描述】:

我正在尝试向 IIS 中托管的 webapi 应用程序发送发布请求。我总是在发布请求时收到错误 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 调用发布请求:

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

发布方式:

[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);
      
      [...]
    
   [...]

邮递员请求:

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

为此花费了几个小时。由于我缺乏答案,我将非常感谢您的帮助。

【问题讨论】:

可能是你的 ajax 函数。尝试添加 type = "POST" 谢谢。我已更新 Ajax 帖子代码库以供您查看 【参考方案1】:

您的 ajax 后请求有一个包

    url: "/Survey/CreateSurvey/",

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

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

   url: "/Aella/Create/",

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

【讨论】:

我将surveyCode参数传递给get方法,以便更新模型并在成功时呈现视图 谢谢,但是如何调用 Post 方法呢?你能显示代码吗? 感谢您的关注。我已更新代码供您查看。 @hopeforall。谢谢,但我还是看不到你的观点 我已经更新了代码。正确的网址是“/Aella/Create”【参考方案2】:

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

【讨论】:

以上是关于MVC Post 请求始终返回 IIS 错误 500,但适用于邮递员的主要内容,如果未能解决你的问题,请参考以下文章

通过 AJAX POST 请求(IIS 7、ASP.NET MVC 4)向服务器传递大文件时出错

部署在 IIS 上的 ASP.NET Core 对长时间运行的请求返回 502 错误

IIS Express 在调试 ASP.NET MVC 时出现拒绝访问错误

Asp.net core MVC post 参数始终为空

windows iis 禁用除了GET和POST之外的请求方法

通过 iis 上的 python 脚本处理带有 json 的 http post 请求