首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVC Post请求始终返回IIS错误500,但适用于邮递员

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

Stack Overflow用户
提问于 2021-11-03 12:20:10
回答 2查看 75关注 0票数 0

我正在尝试向IIS中承载的webapi应用程序发送post请求。对于post请求,我总是得到错误500,但get请求工作正常。下面是我的代码

型号:

代码语言:javascript
运行
复制
  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代码:

代码语言:javascript
运行
复制
$(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请求:

代码语言:javascript
运行
复制
$('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);
        }
    });
});

Get请求:

代码语言:javascript
运行
复制
    [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方法:

代码语言:javascript
运行
复制
[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);
      }
      [...]
    }
   [...]
}

邮递员请求:

代码语言:javascript
运行
复制
    {
    "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":""
        }
    ]
}

表单(主视图):

代码语言:javascript
运行
复制
@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>
        }

局部视图:

代码语言:javascript
运行
复制
@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>

来自服务器的响应:

代码语言:javascript
运行
复制
    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."}

在这上面花了几个小时。我真的很感谢你的帮助,因为我缺少答案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-03 12:28:56

您的post ajax请求有一个包

代码语言:javascript
运行
复制
    url: "/Survey/CreateSurvey/",

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

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

代码语言:javascript
运行
复制
   url: "/Aella/Create/",

修复这些错误后,尝试一步一步地调试应用程序的其他部分。因为我可以在你的局部视图中看到很多我以前从未见过的html助手,我不确定它们是否生成了可以提交的正确的mvc html。因此,我建议首先对部分视图进行注释,并尝试将工作视图作为主视图。在此之后,您可以继续使用局部视图逐行添加。

票数 0
EN

Stack Overflow用户

发布于 2021-11-04 22:31:32

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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69824737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档