Blazor Wasm 托管错误 抱歉,此地址中没有任何内容



尝试在服务器端控制器中调用API方法时出现以下错误

我哪里做错了。

另外,当我调用/swagger"时,我也得到&;对不起,这个地址没有任何东西

index.razor

var httpclient = new HttpClient();
httpclient.BaseAddress = new Uri("https://localhost:7191/");
var result =  httpclient.GetStringAsync($"api/Account/LoginUser?userName={userName}&Email={Email}");

我的控制器

using BlazorChatApp.Shared;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace BlazorChatApp.Server.Controllers
{

[Route("api/[controller]/[action]")]
[ApiController]
public class AccountController : ControllerBase
{

[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> LoginUser(string userName, string Email)
{


var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, userName),
new Claim(ClaimTypes.Email, Email),
new Claim("UserDefined", "whatever"),
};

var claimsIdentity = new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
// await HttpContext.SignInAsync(claimsPrincipal);
// await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties { IsPersistent = true });
await HttpContext.SignInAsync(
JwtBearerDefaults.AuthenticationScheme,
claimsPrincipal,
new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = true,
AllowRefresh = true,
IssuedUtc = DateTimeOffset.Now
});
return Ok(new User());
}
}
}

服务器端程序。cs

using BlazorChatApp.Server;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSignalR();
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddAuthentication(options =>
{
// Identity made Cookie authentication the default.
// However, we want JWT Bearer Auth to be the default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
// Configure the Authority to the expected value for
// the authentication provider. This ensures the token
// is appropriately validated.
options.Authority = "https://testApp:888"; // TODO: Update URL
// We have to hook the OnMessageReceived event in order to
// allow the JWT authentication handler to read the access
// token from the query string when a WebSocket or 
// Server-Sent Events request comes in.
// Sending the access token in the query string is required due to
// a limitation in Browser APIs. We restrict it to only calls to the
// SignalR hub in this code.
// See https://learn.microsoft.com/aspnet/core/signalr/security#access-token-logging
// for more information about security considerations when using
// the query string to transmit the access token.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/chathub")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});

builder.Services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseResponseCompression();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerTest"));
//app.UseSwaggerUI();
//app.UseSwaggerUI(options =>
//{
//    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
//    options.RoutePrefix = string.Empty;
//});
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapFallbackToFile("index.html");
});

app.Run();

对于我来说,这是由于我删除了Index。剃刀页面,然后重新添加回来。

上面的操作导致这些行被添加到.csproj文件中:

<ItemGroup><Content Remove="PagesIndex.razor" />
</ItemGroup>
<ItemGroup><None Include="PagesIndex.razor" />
</ItemGroup>

手动从csproj文件中删除上述行后,一切又正常了。

如果您正在调试Visual Studio中的解决方案,并且不小心将WASM客户端项目设置为启动项目,则会得到"对不起,此地址没有任何内容";对于你认为的服务器端请求。这是因为服务器不会启动,而Blazor将接收所有请求。

相关内容

最新更新