简体   繁体   中英

HttpHead in ASP.NET Core

In my ASP.NET core Controller I've got the following HttpGet-function:

[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. IE sends a HEAD request first. The HEAD request Fails, so IE does not even try to get the PDF. Other browsers do not send HEAD or use GET when HEAD fails, but not IE.

Since I want so Support IE I want to create a HEAD Action. 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.").

So how do I create a HttpHead-Verb-Function in ASP.NET Core? 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");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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