【问题标题】:ASP.NET MVC - 406 Not Acceptable on return View()ASP.NET MVC - 返回 View() 时 406 不可接受
【发布时间】:2020-05-09 17:51:06
【问题描述】:

我无法弄清楚为什么我使用一个简单的 .NET Core 应用程序会收到 406 Not Acceptable 错误代码。

这是调用代码的 HTTP 请求:

POST /my HTTP/1.1
Host: localhost:44350
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept: text/html, text/plain, */*
Connection: close
Referer: https://localhost:44350/fetch-data
Content-Type: application/json
Content-Length: 35

{ "searchTerm" :  "cookie",
 }

这是 HTTP 响应:

HTTP/1.1 406 Not Acceptable
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Sat, 09 May 2020 17:46:38 GMT
Connection: close
Content-Length: 0

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace test_dotnet_angular.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [Produces("text/html")]
    public class MyController : Controller
    {
        public MyController()
        { }

        [HttpPost]
        public ViewResult Post([FromBody] My data)
        {
            ViewBag.SearchTerm = data.searchTerm;
            return View("View");

        }
    }
}

模型:

using System;

namespace test_dotnet_angular
{
    public class My
    {
        public string searchTerm { get; set; }
    }
}

观点:

@{
    ViewData["Title"] = "Search Results";
    ViewData["Content-Type"] = "text/html";
}

<h1>Search Results</h1>
You searched for @ViewBag.SearchTerm

我知道我一定错过了一些愚蠢的东西。我是.NET 的新手。我做了很多搜索,但几乎所有内容都与 JSON 返回类型有关。我在返回视图结果中找到的所有示例看起来都像我正在做的事情。我不明白我必须遗漏哪些小细节。

【问题讨论】:

  • 您使用的是什么版本的 .net core?
  • 您有一个请求标头Accept: application/json, text/plain,而在控制器中,它在Produces 属性中显示text/html
  • @YegorAndrosov 3.1
  • @Saravanan 最后带有通配符,我认为它通常会处理它;但只是为了确保我尝试手动将其更改为 text/html 并且它的行为仍然相同。我将更新示例以匹配,因为我确信这看起来很奇怪。

标签: c# .net asp.net-mvc


【解决方案1】:

JSON 中的逗号使 ASP.NET Core MVC 返回 406 Not Acceptable。

这不起作用:

{ 
    "searchTerm" :  "cookie",
}

这是有效的:

{ 
    "searchTerm" :  "cookie"
}

【讨论】:

  • 哇。我知道这很简单。谢谢!只要它允许我,我就会接受这个答案。我不敢相信这对这个错误产生了影响。
  • 这是 Core MVC 的奇怪行为!
猜你喜欢
  • 2015-07-10
  • 2013-04-26
  • 2011-11-12
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
相关资源
最近更新 更多