ASP.NET Core 中的 HttpHead

Sam*_*Sam 7 c# http-head asp.net-core

在我的 ASP.NET 核心控制器中,我有以下 HttpGet 函数:

[HttpGet("[action]")]
[HttpHead("[action]")]
[ResponseCache(NoStore = true)]
public async Task<IActionResult> GetProofPdf(long studentid)
{
  var rawPdfData = await _studentLogic.StudentPdfAsync(User, studentid);
  if (Request.Method.Equals("HEAD"))
  {
    Response.ContentLength = rawPdfData.Length;
    return Json(data: "");
  }
  else
  {
    return File(rawPdfData, "application/pdf");
  }
}
Run Code Online (Sandbox Code Playgroud)

这确实工作得很好。返回的文件对象可以从浏览器保存。唯一的问题是在 IE 中嵌入 PDF。IE首先发送HEAD请求。HEAD 请求失败,因此 IE 甚至不会尝试获取 PDF。其他浏览器在 HEAD 失败时不会发送 HEAD 或使用 GET,但 IE 不会。

因为我想要支持 IE,所以我想创建一个 HEAD 操作。仅添加[HttpHead("[action]")]到该函数是行不通的,可能是因为对于 HEAD 来说,内容必须为空(“HEAD 方法与 GET 相同,只是服务器不得在响应中返回消息正文。”)。

那么如何在 ASP.NET Core 中创建 HttpHead-Verb-Function?如何返回空内容但返回正确的内容长度?

Muq*_*han 6

这些方面的东西应该对你有用。

    [HttpGet]
    [HttpHead]
    [ResponseCache(NoStore = true)]
    public async Task<IActionResult> GetProofPdf(long studentid)
    {
        if (Request.Method.Equals("HEAD"))
        {
            //Calculate the content lenght for the doc here?
            Response.ContentLength = $"You made a {Request.Method} request".Length;
            return Json(data: "");
        }
        else
        {
            //GET Request, so send the file here.
            return Json(data: $"You made a {Request.Method} request");
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • @Sam你实际上正在返回一些数据,尝试使用 return Ok() 而不是 Json(data: ""); (5认同)