簡體   English   中英

ASP.NET Core Web API 錯誤請求

[英]ASP.NET Core Web API Bad Request

我有點困惑 - 我創建了一個 ASP.NET Core Web API MVC 項目,但是當我嘗試提出請求時,我得到以下響應:

我正在向https://localhost:44337/api/Solve 發布以下正文:

{
    "examId":"0f537776-1acf-478f-82ee-c8476bc3e005",
    "selectedAnswers":
    [
        {
            "id":"9163fd1c-ec0f-4f1f-8ead-05ffeac36426",
            "answerText":"Yes",
            "isCorrect":true

        },
        {
            "id":"00545a13-212b-46a5-9d06-3f6abbb9f1d8",
            "answerText":"Yes",
            "isCorrect":true
        }
    ]
}

並收到此作為回復:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "Bad Request",
    "status": 400,
    "traceId": "8000005f-0001-ff00-b63f-84710c7967bb"
}

我已經包含了 Content-Type。 GlobalConstants.RouteConstants.ApiRoute = "api/" GlobalConstants.RouteConstants.PostSolve = "Solve" 這是我的控制器:


    [Route(GlobalConstants.RouteConstants.ApiRoute)]
    [ApiController]
    public class ESchoolController : ControllerBase
    {
        protected IApiService ApiService { get; set; }

        public ESchoolController(IApiService apiService)
        {
            this.ApiService = apiService;
        }

        //POST: api/Solve
        [HttpPost]
        [Route(GlobalConstants.RouteConstants.PostSolve)]
        public IActionResult Solve([FromBody]ExamApiSolveInputModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest();
            }

            try
            {
                var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                var result = this.ApiService.SolveExam(model, userId);
                return this.Ok(result);
            }
            catch (Exception e)
            {
                return this.BadRequest(e.Message);
            }
        }
    }

這是我的輸入模型:

    public class ExamApiSolveInputModel
    {
        public ExamApiSolveInputModel()
        {
            this.SelectedAnswers = new List<AnswerApiInputModel>();
        }

        public string ExamId { get; set; }

        public ICollection<AnswerApiInputModel> SelectedAnswers { get; set; }
    }

    public class AnswerApiInputModel
    {
        public string Id { get; set; }

        public string AnswerText { get; set; }

        public bool IsCorrect { get; set; }
    }

我一直在尋找解決方案,但沒有成功。 我嘗試過一些事情,例如:

  1. 當我提出請求時,它沒有進入控制器。 我已經用調試器檢查過了。
  2. 制作另一個 post 方法,但它又不是通過調試器輸入代碼,所以我認為問題不在代碼中。

任何想法如何解決這個問題? 非常感謝,節日快樂!

您需要提供更多信息,您將如何提出請求。

確保在正文中包含 JSON 並將Content-Type標頭設置為"application/json"

我從Startup.cs文件中刪除了services.AddMvc(options => services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));問題消失了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM