Search code examples
c#asp.netrazor-pages

call API from razor page on button press


I have a razor page server using asp.net and I need to call the api from a button press, I have been struggling with this for longer than I am willing to admit, so I am just gonna give you the code here. I know that the API communication itself works, since I have another console app where it works just fine. I need to call the API on a button press and then show the result on the page itself. It would really help if someone could also tell me how to do it with arguments (the argument being the filepath..), thanks in advance.

I tried pretty much everything it seems to me, but it still doesnt work, Im completely new to razor pages and Im never gonna do anything with them after this, but I need this done. Test.cshtml.cs:

using Google.Cloud.DocumentAI.V1;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc;
using Google.Protobuf;
using System.Diagnostics;

namespace MyApp.Namespace
{
    public class DocumentViewModel : PageModel
    {
        public Document ProcessedDocument { get; private set; }
        public bool IsDocumentProcessed { get; set; }

        public void OnGet()
        {
            
        }

        public async Task<IActionResult> OnPost(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                ModelState.AddModelError("filePath", "File path is required.");
                return Page();
            }

            try
            {
                // Call to Document AI API
                ProcessedDocument = Quickstart(filePath);
                IsDocumentProcessed = true;
            }
            catch (Exception ex)
            {
                
                IsDocumentProcessed = false;
                ModelState.AddModelError("", "Failed to process document: " + ex.Message);
            }

            return Page();  
        }



        public Document Quickstart(
        string localPath,
        string projectId = "...",
        string locationId = "eu",
        string processorId = "...",
        string mimeType = "application/pdf")
    {
        var client = new DocumentProcessorServiceClientBuilder
        {
            Endpoint = $"{locationId}-documentai.googleapis.com"
        }.Build();

        using var fileStream = System.IO.File.OpenRead(localPath);
        var rawDocument = new RawDocument
        {
            Content = ByteString.FromStream(fileStream),
            MimeType = mimeType
        };

        var request = new ProcessRequest
        {
            Name = ProcessorName.FromProjectLocationProcessor(projectId, locationId, processorId).ToString(),
            RawDocument = rawDocument
        };

        var response = client.ProcessDocument(request);

        var document = response.Document;
        return document;
    }
    }
}

Test.cshtml:

@page
@model MyApp.Namespace.DocumentViewModel

@{
    ViewData["Title"] = "Document Processing";
}

<h1>Document Processing</h1>

<form method="post">
    <div class="form-group">
        <label for="filePath">Enter file path:</label>
    </div>
    <button type="submit" class="btn btn-primary">Process Document</button>
</form>


@if (Model.IsDocumentProcessed)
{
    <h2>Processed Document Content</h2>
    if (Model.ProcessedDocument != null)
    {
        <div>
            <p>Text from the document:</p>
            <pre>@Model.ProcessedDocument.Text</pre>
        </div>
    }
    else
    {
        <p>No content available or processing failed.</p>
    }
}
else
{
    <p>Submit a document for processing.</p>
}
<style>
    /* Additional CSS styles if needed */
</style>

Please, dont hate on me, I know this is probably trivial, but I really cant figure it out


Solution

  • You can call the action directly form the form

    <form asp-action="OnPost" method="post">
    <div class="form-group">
        <label for="filePath">Enter file path:</label>
        <input type="file" id="customFile" name="filePath">
    </div>
    <button type="submit" class="btn btn-primary">Process Document</button>
    

    Then I will modify the action in this way.

    [HttpPost]
        public IActionResult OnPost(IFormFile File){ 
            string filePath=File.FileName;
            your code here...
        }
    

    In this way you will have directly the file in your code. I hope this can help.