本文介绍了如何向服务器端 Blazor 项目添加控制器(而非视图)支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的服务器端 Blazor 应用程序正在运行时,我希望 _Host.cshtml 中的一些 Javascript 代码能够将数据发布到控制器操作.当然,这完全超出了 Blazor 应用本身的范围,也与 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 项目添加控制器(而非视图)支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 17:04