问题描述
我的服务器端Blazor应用程序正在运行时,我希望 _Host.cshtml
中的一些Javascript代码能够将数据发布到控制器操作中.当然,这完全不在Blazor应用本身的范围之内,而且与之无关.
While my server-side Blazor app is running, I want some Javascript code in _Host.cshtml
to be able to post data to a controller action. Of course, this happens completely outside of the scope of, and is unrelated to, the Blazor app itself.
我认为这是在 Startup.cs中适当位置添加对
.但是,在完成此操作并执行了控制器动作之后,我做了以下观察: services.AddControllers()
和 endpoints.MapControllers()
的调用的问题
I thought this would be a matter of adding calls to services.AddControllers()
and endpoints.MapControllers()
at the appropriate places in Startup.cs
. However, after doing this, and implementing the controller action, I made the following observations:
- 对该操作的请求未路由并被视为未找到"
- 在Razor中,控制器操作上的
@ Url.Action
返回空字符串
- Requests to the action are not routed and treated as "not found"
- In Razor,
@Url.Action
on the controller action returns a blank string
如何通过克服上述两个问题的方式向服务器端Blazor项目添加控制器(而非视图)支持?
How can I add controller (not view) support to my server-side Blazor project in a way that overcomes the above two issues?
推荐答案
使用: endpoints.MapControllers()
您可以在startup.cs中添加它:
You can have this in your startup.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
此控制器:
[Route("api/[controller]")]
[ApiController]
public class DownloadController : Controller
{
private readonly IWebHostEnvironment environment;
public DownloadController(IWebHostEnvironment environment)
{
this.environment = environment;
}
[HttpGet("[action]")]
public IActionResult DownloadFile(string FileName)
{
string path = Path.Combine(
environment.WebRootPath,
"files",
FileName);
var stream = new FileStream(path, FileMode.Open);
var result = new FileStreamResult(stream, "text/plain");
result.FileDownloadName = FileName;
return result;
}
}
这在您的.razor页面中:
And this in your .razor page:
@inject NavigationManager NavigationManager
<button @onclick="DownloadFile">Download</button>
@code {
public void DownloadFile()
{
NavigationManager.NavigateTo($"/api/Download/DownloadFile?FileName=BlazorHelpWebsite.zip", true);
}
}
请参阅: https://github.com/ADefWebserver/Blazor-Blogs/tree/master/BlazorBlogs
这篇关于如何向服务器端Blazor项目添加控制器(而非视图)支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!