简体   繁体   English

ASP.NET Core中的HttpHead

[英]HttpHead in ASP.NET Core

In my ASP.NET core Controller I've got the following HttpGet-function: 在我的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");
  }
}

This does work nicely. 这确实很好。 The returned file object can be saved from the browser. 可以从浏览器保存返回的文件对象。 The only problem is embedding the PDF in IE. 唯一的问题是将PDF嵌入IE。 IE sends a HEAD request first. IE首先发送HEAD请求。 The HEAD request Fails, so IE does not even try to get the PDF. HEAD请求失败,因此IE甚至不会尝试获取PDF。 Other browsers do not send HEAD or use GET when HEAD fails, but not IE. 其他浏览器不会在HEAD失败时发送HEAD或使用GET,但不会发送IE。

Since I want so Support IE I want to create a HEAD Action. 因为我要这样支持IE,所以我想创建一个HEAD动作。 Just adding [HttpHead("[action]")] to the function will not work, probably because for HEAD the content must be empty ("The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response."). 仅将[HttpHead("[action]")]到该函数将不起作用,这可能是因为HEAD的内容必须为空(“ HEAD方法与GET相同,只是服务器必须在该方法中不返回消息正文。响应。”)。

So how do I create a HttpHead-Verb-Function in ASP.NET Core? 那么,如何在ASP.NET Core中创建HttpHead-Verb-Function? How do I return empty Content but the correct content-length? 如何返回空内容,但内容长度正确?

Something along these lines should work for you. 遵循这些原则应该可以为您工作。

    [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");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM