Sam
Sam

Reputation: 976

Use ASP.NET Core Web API with an app that's not using MVC

Is it possible to use Web API within a .NET Core application that is not using MVC, but making use of app.Run?

I want to provide a simple API and would rather use Web API than roll my own. I've added in MvcCore in ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        // ...
        services.AddMvcCore(x =>
        {
            x.RespectBrowserAcceptHeader = true;
        }).AddFormatterMappings()
        .AddJsonFormatters();

        // ...
    }

I added a very simple Controller:

[Route("/api/test")]
public class TestController : Controller
{
    [HttpGet]
    [Route("")]
    public async Task<IActionResult> Get()
    {
        return Ok("Hello World");
    }
}

However, when I attempt to hit /api/test my normal processing code within App.Run processes.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var scopeFactory = _serviceProvider.GetRequiredService<IServiceScopeFactory>();

        // ...

        app.Run(async (context) =>
        {
            using (var scope = scopeFactory.CreateScope())
            {
                var request = new Request(context);
                var response = new Response(context);

                await scope.ServiceProvider.GetRequiredService<IRequestFactory>().ProcessAsync(request, response);
            }
        });
    }

How do I defer to the Web API if I don't want to handle the request?

Upvotes: 0

Views: 165

Answers (1)

Rohith
Rohith

Reputation: 5677

In order to configure MVC,you have to add it both in ConfigureServices and Configure like below

ConfigureServices

 public void ConfigureServices(IServiceCollection services)
        {      
            services.AddMvc();
        }

Configure

  public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }

So in your code,you have only done the first part.

Also I see that you have used app.Run ,do not use Run if you have other middlewares to run.app.Run delegate terminates the pipeline and MVC middleware will not get chance to execute

What you have to do is to change the code to app.Map ,refer this article for the user of Run,use and map

So the order of middleware matters. you have to change the code like this

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        var scopeFactory = _serviceProvider.GetRequiredService<IServiceScopeFactory>();

        // ...

        app.Use(async (context,next) =>
        {
            using (var scope = scopeFactory.CreateScope())
            {
                var request = new Request(context);
                var response = new Response(context);

                await scope.ServiceProvider.GetRequiredService<IRequestFactory>().ProcessAsync(request, response);
            }
          await next.Invoke()

        });
       app.UseMvc();
    }

Upvotes: 1

Related Questions