0

Given an MVC controller method, that builds and returns a PDF.

    [HttpGet]
    [Route("pdf/{acc}/{sign}")]
    public async Task<ActionResult> Download(string acc, string sign)
    {
        ... // omitted some irrelevant detail.
        var html = this.View("Letter", model).Capture(this.ControllerContext);
        byte[] pdf = this.CreatePdfFromHtml(html);
        return this.File(binary, "application/pdf", file);
    }

The Capture extension method captures the html output, which is then returned as a file.

I need to execute the above method (or something close) in the below webapi2 method. I need the credentials and other login state to be present. The webapi and MVC requests are within the same application that uses cookies for security.

    [HttpPost]
    [Route("generate")]
    public int Generate(MyRequestModel request)
    {
        byte[] pdf = ... // how do i get the file above??
    }

1 Answer 1

2

You should either request the MVC action via HttpClient or simply factor out the PDF creation into a helper class that both your MVC and Web Api actions can reference.

With the first method, you would need to some how authenticate the request, which is going to be a bit difficult to do with an MVC action. MVC uses a multi-step authorization: sign in, verify, set cookie, redirect. You would have to follow those same steps in order to get a cookie set via HttpClient. Think of it as a little mini-browser. Web Api, on the other hand, simply accepts an Authorization header, since API requests are idempotent.

The easiest and most straight-forward route, especially since both your MVC and Web Api reside in the same application, would be to simply factor out the PDF creation code into a helper class. Your MVC and Web Api actions, then, can simply just call some method on that class to get the PDF, reducing code duplication.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Chris - problem is that's the PDF is generated by capturing HTML from an mvc view, so factoring out the PDF generation code is exactly the problem. I might have to go with creating a client - which does seem like a lot of hoops....
I think I will just call a regular MVC method from angular, it's really just for consistency that I want to use webapi.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.