Home > database >  How to Send Request from MInimaApi instance to another MVC instance
How to Send Request from MInimaApi instance to another MVC instance

Time:01-17

I'm trying to create API working by minimalApi service who can be accessible from public and can send GET/POST/PUT request to my Web Service with Controllers.

But every time when I Send GET to my controller, I receive status code 200 (OK) even when i sure that action from controller 100% always must return bad request, I'm assuming that no request was actually sent. When I'm trying to send POST or PUT, I get status code 405 (Method not allowed) So I don't have idea how to send any request to another web service.

My Simple minimalAPi action :

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

And my Controller from other side :

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

After research, I assumed that problem is because of CORS, And tried to configure CORS on both sides. And it looks good for me, but it still doesn't work.

CORS Config on MinimalApi Web application Side :

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

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

app.UseCors("cors");

CORS config on MVC Web application :

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

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

CodePudding user response:

For some Reason, I can't directly call the server side controller in blazor, I bypassed this problem manually configured Get Action in Endpoints

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