将表单数据发布到 Blazor razor 组件 (application/x-www-form-urlencoded)

BLe*_*ing 2 asp.net-core blazor blazor-server-side asp.net-blazor blazor-webassembly

我刚刚开始学习 Blazor,所以如果问题很奇怪,请耐心等待。

是否可以将数据作为内容类型“application/x-www-form-urlencoded”发布到 Blazor razor 组件,以便在浏览器中打开页面时,它将显示调用者提供的初始值?当使用查询字符串并使用 HTTP GET 方法并在 navigationManager 的帮助下调用 razor 组件 url 时,它效果很好。在这种情况下,我无法更改数据的发送方式。我需要能够使用内容类型 application/x-www-form-urlencoded 处理 HTTP POST 调用,并且主体提供初始值作为 key=value。加载页面时,数据应显示在屏幕上。然后应该在页面上为用户提供一些选项,并通过单击按钮进行选择。

如果这不可能,那么满足此特定要求的正确方法是什么,即无法更改数据的发送方式(必须是内容类型为 application/x-www-form-urlencoded 的 HTTP POST)并且接收应用程序为 Blazor。

更新:Blazor 应用程序最好是服务器端的,但如果需要,可以更改为 Web 程序集(客户端)。

hil*_*lin 6

在 Blazor Server 中,应用内导航是通过 websocket 完成的,没有发出 HTTP 请求,因此没有GETPOST操作。您只能处理外部 HTTP 请求,这应该正是所讨论的情况。

Blazor 组件,或者实际上是 Razor 组件,尽管其中一些组件的行为类似于带有@page标签的页面,但它们只是组件。它们不是独立存在的,而是必须托管在Razor Page中,即默认情况下的_Host.cshtml中。对 Blazor 应用程序的任何外部 HTTP 请求实际上都是对托管页面的请求,托管页面又根据请求 URI加载相应的页面组件。这些请求在组件中看不到,但可以在托管页面中处理,因为它只是一个普通的旧 Razor 页面。

去做这个:

  1. 创建一个PostFormService在主机页面和组件之间传递帖子表单的:
using Microsoft.AspNetCore.Http;

public class PostFormService
{
    public IFormCollection? Form { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
  1. 将 注册PostFormService到 DI。在Startup.csConfigureServices的方法中添加:
services.AddScoped<PostFormService>();
Run Code Online (Sandbox Code Playgroud)
  1. 将以下代码块添加到您的主页:
@using Microsoft.AspNetCore.Mvc.RazorPages;

<!-- ignore anti-forgery token for external post requests -->
@attribute [IgnoreAntiforgeryToken]

<!-- specify model for the page -->
@model HostPageModel

@{

public class HostPageModel : PageModel
{
    // postFormService is injected by the DI
    public HostPageModel(PostFormService postFormService)
    {
        PostFormService = postFormService;
    }

    private PostFormService PostFormService { get; }

    public void OnPost()
    {
        // store the post form in the PostFormService
        PostFormService.Form = Request.Form;
    }

}

}
Run Code Online (Sandbox Code Playgroud)
  1. 现在您可以注入PostFormServiceRazor 组件并访问请求表单:
@inject PostFormService PostFormService;
@code{
    protected override void OnInitialized()
    {
        base.OnInitialized();

        // PostFormService.Form will be null if the page is not requested by 
        // a POST method
        var data = PostFormService.Form?["data"];
        Console.WriteLine(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你是一位圣人,这应该是公认的答案,效果完美。 (2认同)