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

前端 未结 1 2079
囚心锁ツ
囚心锁ツ 2021-02-14 19:11

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 comp

1条回答
  •  生来不讨喜
    2021-02-14 19:45

    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
    
    
    
    @code {
         public void DownloadFile()
        {
            NavigationManager.NavigateTo($"/api/Download/DownloadFile?FileName=BlazorHelpWebsite.zip", true);
        }
    }
    

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

    0 讨论(0)
提交回复
热议问题