【问题标题】:An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set. in Blazor提供了无效的请求 URI。请求 URI 必须是绝对 URI,或者必须设置 BaseAddress。在 Blazor
【发布时间】:2019-10-10 06:31:12
【问题描述】:

遇到控制器异常错误时出现“提供了无效的请求 URI。请求 URI 必须是绝对 URI 或必须设置 BaseAddress。”****strong text

blazor 服务器端

控制器调用不在 Razor 组件中执行 查看代码

  async Task UploadFile()
  {
    try
    {
      LoginRepository loginRepository = new LoginRepository(new LaborgDbContext());
      DocumentService documentService = new DocumentService();
      var form = new MultipartFormDataContent();
      var content = new StreamContent(file.Data);
      content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
      {
        Name = "files",
        FileName = file.Name
      };
      form.Add(content);
      var response = await HttpClient.PostAsync("/api/Document/Upload", form);    
    }
    catch (Exception ex)
    {
      throw ex;
    }

  }

控制器代码

[Route("api/[controller]/[action]")]
  [ApiController]
  public class UploadController : ControllerBase
  {
    private readonly IWebHostEnvironment _Env;

    public UploadController(IWebHostEnvironment env)
    {
      _Env = env;
    }
    [HttpPost()]
    public async Task<IActionResult> Post(List<IFormFile> files)
    {
      long size = files.Sum(f => f.Length);
      foreach (var formFile in files)
      {
        // full path to file in temp location
        var filePath = Path.GetTempFileName();
        if (formFile.Length > 0)
        {
          using (var stream = new FileStream(filePath, FileMode.Create))
          {
           await formFile.CopyToAsync(stream);
          }
        }

        System.IO.File.Copy(filePath, Path.Combine(_Env.ContentRootPath, "Uploaded", formFile.FileName)); 
      }

      return Ok(new { count = files.Count, size });
    }

启动

  public class Startup

{ 公共启动(IConfiguration 配置) { 配置=配置; }

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
  services.AddAuthorizationCore();
  services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(
          Configuration.GetConnectionString("DefaultConnection")));
  services.AddDefaultIdentity<IdentityUser>()
      .AddEntityFrameworkStores<ApplicationDbContext>();
  services.AddRazorPages();
  services.AddServerSideBlazor();
  services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
  services.AddSingleton<WeatherForecastService>();
  services.AddSingleton<TaskSchedulerService>();
  services.AddSingleton<TimeOffSchedulerService>();
  services.AddSingleton<DocumentService>();
  services.AddFileReaderService(options => options.InitializeOnFirstCall = true);
  services.AddSingleton<HttpClient>();

  services
.AddBlazorise(options =>
{
  options.ChangeTextOnKeyPress = true; // optional
})
.AddBootstrapProviders()
.AddFontAwesomeIcons();
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseDatabaseErrorPage();
  }
  else
  {
    app.UseExceptionHandler("/Error");

    app.UseHsts();
  }

  app.UseHttpsRedirection();
  app.UseStaticFiles();

  app.UseRouting();
  app.UseEmbeddedBlazorContent(typeof(MatBlazor.BaseMatComponent).Assembly);
  app.UseEmbeddedBlazorContent(typeof(BlazorDateRangePicker.DateRangePicker).Assembly);
  app.UseAuthentication();
  app.UseAuthorization();

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

} }

【问题讨论】:

  • 请出示您的Startup.cs代码
  • 包含 Startup.cs

标签: asp.net-core asp.net-apicontroller blazor-server-side


【解决方案1】:

startup.cs 页面并将以下代码添加到 app.UseEndpoints 方法的末尾(在 endpoints.MapFallbackToPage("/_Host"); 行下),以允许正确路由对控制器的 http 请求。

添加以下行 endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

app.UseEndpoints(endpoints =>
      {
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
      });

【讨论】:

  • 我有同样的问题我的启动页面除了单例之外是相同的但是,当我尝试调用 Http.PostJsonAsync 我得到相同的错误消息 - 还有其他想法吗?我使用 vs 2019 创建了一个新的服务器端 blazor 应用程序
【解决方案2】:

https://github.com/dotnet/aspnetcore/issues/16840

当位置包含 %20 时 Blazor 抛出

来自:@msftbot

我们已将此问题移至待办事项里程碑。这意味着它不会在即将发布的版本中使用。我们将在当前版本之后重新评估积压,并在那时考虑这个项目。

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 1970-01-01
    • 2021-09-30
    • 2020-01-07
    • 2019-01-15
    • 2021-07-30
    • 2018-10-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多