【发布时间】: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