【问题标题】:How to call a controller inside a Razor Class Library如何在 Razor 类库中调用控制器
【发布时间】:2021-11-12 04:10:43
【问题描述】:

我有一个用控制器定义的 RCL。 我们称它为 DataController,它是这样定义的:

[Route("[controller]")]
    public class DataController : Controller
    {
        [HttpGet("[action]")]
        public async Task<ActionResult<List<string>>> LetsBreakIt()

此控制器放置在库根级别的名为 Controllers 的文件夹中。 从 Razor 组件中,我尝试以下代码:

string uri = $"Data/LetsBreakIt";

        try
        {
            var client = new HttpClient();
            ssiList = await client.GetFromJsonAsync<List<string>>(uri);
        }
        catch (Exception ex)

但我有这个错误:

提供的请求 URI 无效。请求 URI 必须是 必须设置绝对 URI 或 BaseAddress。

当然,我尝试设置以“/”开头的 uri,但它给了我同样的错误。 我尝试添加(没有成功):

[ApiController]

在我的 Blazor 应用程序中,在 startup.cs 中,这是当前映射的内容:

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

【问题讨论】:

    标签: .net-core razor controller blazor


    【解决方案1】:

    答案是使用 NavigationManager 获取基础 URI,然后使用它:

        var absoluteUri = NavigationManager.ToAbsoluteUri("Data/LetsBreakIt");
        
        try
        {
            var client = new HttpClient();
            client.BaseAddress = absoluteUri;
            ssiList = await client.GetFromJsonAsync<List<string>>("");
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2013-06-12
      • 2014-03-09
      • 2013-11-21
      • 2019-03-24
      • 1970-01-01
      相关资源
      最近更新 更多