我有一个使用 asp.net 的 razor 页面服务器,我需要通过按下按钮来调用 api,我在这个问题上挣扎的时间比我愿意承认的要长,所以我只是在这里给你代码。我知道 API 通信本身可以正常工作,因为我有另一个控制台应用程序,它可以正常工作。我需要在按下按钮时调用 API,然后在页面本身上显示结果。如果有人也可以告诉我如何使用参数(参数是文件路径..),那真的会有帮助,提前谢谢。
我几乎尝试了我认为的所有方法,但它仍然不起作用,我对剃刀页面完全陌生,此后我永远不会对它们做任何事情,但我需要完成此操作。 测试.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;
}
}
}
测试.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>
请不要讨厌我,我知道这可能是微不足道的,但我真的无法弄清楚
您可以直接从表单调用操作
<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>
然后我会这样修改动作。
[HttpPost]
public IActionResult OnPost(IFormFile File){
string filePath=File.FileName;
your code here...
}
通过这种方式,您将直接在代码中拥有该文件。 我希望这能有所帮助