How to add controller (not view) support to a server-side Blazor project

主宰稳场 提交于 2021-02-07 02:36:07

问题


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.

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:

  • Requests to the action are not routed and treated as "not found"
  • In Razor, @Url.Action on the controller action returns a blank string

How can I add controller (not view) support to my server-side Blazor project in a way that overcomes the above two issues?


回答1:


Use: endpoints.MapControllers()

You can have this in your startup.cs:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
    });

This controller:

[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;
    }
}

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);
    }
}

See: https://github.com/ADefWebserver/Blazor-Blogs/tree/master/BlazorBlogs



来源:https://stackoverflow.com/questions/60022519/how-to-add-controller-not-view-support-to-a-server-side-blazor-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!