我有一个blazor托管的应用程序,用户可以通过填写表单创建一个帐户。创建帐户时,向用户发送带有链接s/他的电子邮件,以确认他/她对电子邮件地址的所有权。链接指向我的服务器中的操作方法。同一台服务器承载了blazor应用程序和API。
问题是,当用户单击该链接时,请求不会发送到服务器。相反,blazor拦截调用并尝试路由到某个页面。
我怎么才能把这事做好?如何使指向服务器中某个操作的链接在单击时实际到达服务器?换句话说,如果可能的话,如何绕过blazor的路由系统?
更新:
Url.Action("actionName", "controllerName", actionParam, Request.Scheme);中的Url属性生成链接。就目前而言,这个链接看起来像是一个post操作。<NotFound />组件(App.razor文件)中的内容。注意:,这不是一个错误。这是balzor wasm的正常行为。如果应用程序是在www.foo.com托管的,那么对foo.com (例如www.foo.com/bar)的所有调用实际上都不会被foo.com调用,而是会被blazor拦截,并被视为到应用程序中页面的路径。然而,这阻碍了我,因为我的API具有与应用程序相同的基本地址(目前,应用程序在localhost:5001/,API在localhost:5001/api/xyz),因此,blazor在我单击链接时阻止了对服务器的调用。问题是如何解决这个问题?如果不可能,我还有什么其他选择来实现这个流程呢?
发布于 2021-03-04 18:54:21
所以我解决了这个问题,把Action方法变成了GET方法,而不是POST。这是相当合乎逻辑的,当你想一想:当用户点击链接s/他收到的电子邮件,将发出一个GET,而不是一个帖子。
我还了解到,blazor只有在地址栏中输入地址时才会将您路由到页面。如果您单击一个链接,请求将被发出。我之所以想blazor拦截请求,是因为单击链接将我重定向到一个页面,但实际上,它只是一个后备机制。您可以在configure方法中看到它:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
// the link clicked issues a GET. My action is a POST.
// So no action is found. It falls back to the index.html
// which is the entery point of my app. Blazor takes over
// from here and tries to find a page for the url requested.
endpoints.MapFallbackToFile("index.html");
});发布于 2021-10-07 08:21:19
我也有过同样的问题。我用JS互操作来修复它。代码是一个显示。
在/wwwroot/index.html中添加以下脚本。
<script>
function downloadfile(filename, fileContent) {
var element = document.createElement('a');
element.setAttribute('href', fileContent);
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
</script>在组件中,在@code中添加以下函数。
private async void DownloadFile(string fileName)
{
//Get the file from the Server Side
//Convert fileName string to String Content
var response = await httpService.PostAsync(
url:"/api/download", content:fileNameStringContent);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
await JSRuntime.InvokeVoidAsync("downloadfile", fileName, content);
}
} 在服务器中添加以下Controller.Action
[HttpPost("download")]
public async Task<string> Download(string fileName)
{
var fileContent = GetFileAsBytes(fileName);
var base64String = "data:application/pdf;base64," + Convert.ToBase64String(fileContent);
return base64String;
}
private async Task<byte[]> GetFileAsBytes(string fileName)
{
try
{
var folderPath = Path.Combine(_env.ContentRootPath, "folder");\
if (!Directory.Exists(folderPath))
return null;
var filePath = Path.Combine(folderPath, fileName);
if (!File.Exists(filePath))
return null;
var fileBytes = await File.ReadAllBytesAsync(filePath);
return fileBytes;
}
catch
{
return null;
}
}https://stackoverflow.com/questions/66466724
复制相似问题