【问题标题】:How to Send Request from MInimaApi instance to another MVC instance如何将请求从 MInimaApi 实例发送到另一个 MVC 实例
【发布时间】:2023-01-17 21:21:07
【问题描述】:

我正在尝试创建由 minimalApi 服务工作的 API,该服务可以从公共访问并且可以使用控制器将 GET/POST/PUT 请求发送到我的 Web 服务。

但是每次当我将 GET 发送到我的控制器时,我都会收到状态代码 200(确定),即使我确定来自控制器的操作 100% 总是必须返回错误的请求,我假设实际上没有发送任何请求。 当我尝试发送 POST 或 PUT 时,我收到状态代码 405(方法不允许) 所以我不知道如何向另一个网络服务发送任何请求。

我的简单 minimalAPI 操作:

  app.MapGet("/SendTestRequest", async ( HttpClient httpClient ) =>
    {
        HttpRequestMessage httpRequestMessage = new() 
        { 
            RequestUri = new Uri($"https://localhost:44313/TestNotification/SendTestRequest"), 
            Method = HttpMethod.Get
        };
        HttpResponseMessage result = await httpClient.SendAsync(httpRequestMessage);
        result.EnsureSuccessStatusCode();
    });

我的控制器来自另一边:

[EnableCors("cors")]
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> SendTestRequest()
{
    return BadRequest();  
}

经过研究,我认为问题是因为CORS,并尝试在两侧配置CORS。它对我来说看起来不错,但它仍然不起作用。

MinimalApi Web 应用程序端的 CORS 配置:

Program.cs...
builder.Services.AddHttpClient();
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "cors",

        policy =>
        {
            policy.AllowAnyOrigin();
            policy.AllowAnyMethod();
        });
});

app.UseCors("cors");

MVC Web 应用程序上的 CORS 配置:

ConfigureServices section ...
        services.AddCors(options =>
        {
            options.AddPolicy(name: "cors",
                policy =>
                {
                    policy.AllowAnyOrigin();
                    policy.AllowAnyMethod();
                    policy.AllowAnyHeader().WithExposedHeaders("*");
                });
        });

 Configure section ... 
            app.UseCors("cors");

【问题讨论】:

  • 此处的 CORS 与任何形状或形式都不相关 - 您没有根据您的请求设置原始标头(并且它不会将错误的请求更改为正常)。
  • 尝试从浏览器调用 https://localhost:44313/TestNotification/SendTestRequest - 它是否按预期返回错误请求?
  • 其返回状态代码 304
  • 因此,无论哪种方式,API 似乎都有些可疑。
  • 然后我需要澄清解决方案的结构。我有 WASM 客户端 + 服务器端 MVC(带有那个目标控制器)并且它们共享相同的地址,我在 MinimalApi 上有一个小的 Web 应用程序,我希望这能帮助你更好地澄清情况

标签: c# .net asp.net-mvc web-services minimal-apis


【解决方案1】:

出于某种原因,我无法直接在 blazor 中调用服务器端控制器,我绕过了这个问题,在 Endpoints 中手动配置了 Get Action

 Configure section ....
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapGet("/test", Test);
                endpoints.MapFallbackToFile("index.html");
                endpoints.MapHub<Hubs.ServerHub>(Hubs.ServerHub.HubUrl);
            });
    
Somewhere in prodject...
            public IResult Test()
            {
                var t = TypedResults.Ok(new Random().Next());
                return t;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多