Blazor - 将参数发送到 API 控制器

Blazor - Sending a Parameter to an API controller

我正在尝试从 mouseOver 事件传递 Url 以使用 HttpGet 提取数据,但我不知道为什么它没有将参数发送到目标 APIcontroller。看看我做了什么。

<div Class="mud-img" style="background-image: url( @items.thumbnail );"
                     height="180" width="300"
                      @onpointerover="@((e) => httpGet(items.href))">
                   <MudIcon Icon="fas fa-play" Size="Size.Large" Style="position:relative" />
                </div>

这就是 EVENT 当鼠标聚焦在 div 上时触发的方法是

 public  async void httpGet(string url)
{
  result =  await Http.GetFromJsonAsync<string>(string.Format("GetYoutubeVid/{0}", url));
}

和目标控制器

 [ApiController]
[Route("GetYoutubeVid")]
public class YouTubeController : ControllerBase
{

    [HttpGet("{url}")]
    
    public string GetYoutubeVid(string url)
    {
        return url;
    }
}

如果我不尝试发送参数,它工作正常(url)

@onpointerover="@((e) => httpGet(items.href))"

我猜这个方法应该有两个参数:第一个是e 这样做:

@onpointerover="@((e) => httpGet(e, items.href))"

并使用两个正确类型的参数定义 httpGet 方法

this part is ok. i am trying to pass this parameter (@((e) => httpGet(e, items.href))") to an api controller

您的 httpGet 方法的签名应如下所示:

public  async Task httpGet(PointerEventArgs args, string url)
 {
     // You should define a public class in the Shared project, so that
     // it can be used in both your front end and Web Api. If you do not 
     // have a Shared project, define this class in both locations. This
     // class should contain the data you can take from the args 
     // parameter, as for instance, args.pointerType, as well as the url
     // parameter... And an instance of this class should be send to the
     // Web Api end point.
     result =  await Http.GetFromJsonAsync<string> 
     (string.Format("GetYoutubeVid/{0}", <An instance of your class>));
}

注意:您应该添加到 div 元素 @onpointerover:preventDefault 以防止鼠标事件被发送

重要:你说的是

I am Trying to pass an Url from a mouseOver event to pull

如果您想像上面所说的那样使用 mouseover 事件,请使用 onmouseover 代替:@onmouseover="@((MouseEventArgs args) => httpGet(args, items.href))"