2

When hitting the controller exception error came "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."****strong text

blazor server side

Controller call not perform in the Razor components View Code

  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;
    }

  }

Controller code

[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 });
    }

start up

  public class Startup

{ public Startup(IConfiguration configuration) { Configuration = configuration; }

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");
  });
}

} }

novfal haq
  • 107
  • 2
  • 16

2 Answers2

1

startup.cs page and add the following code to the end of the app.UseEndpoints method, (under the endpoints.MapFallbackToPage("/_Host"); line), to allow http requests to controllers to be properly routed.

add following line endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

app.UseEndpoints(endpoints =>
      {
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
      });
novfal haq
  • 107
  • 2
  • 16
  • 2
    I have same problem my startup page is identical except singletons however, when I try to call Http.PostJsonAsync i get the same error message - Any other ideas? I have created a new Server Side blazor app using vs 2019 – Eimantas Baigys Dec 20 '19 at 09:46
1

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

Blazor throws when location contains %20

from: @msftbot

We've moved this issue to the Backlog milestone. This means that it is not going to be worked on for the coming release. We will reassess the backlog following the current release and consider this item at that time.

Diego Venâncio
  • 5,698
  • 2
  • 49
  • 68