Nouman Bhatti
Nouman Bhatti

Reputation: 1421

C# - Default index.cshtml as start page in Web Api .Net Core 2.0

I'm developing a Web API project and I need to deploy it on linux server. The requirements of the load balancer on the server is to have a default page.

For that reason I created a Home controller with Index action

[ApiVersion("1.0")]
[Route("/[controller]")]
public class HomeController : Controller
{
   [HttpGet("/")]
   [Route("Home/Index")]
   public IActionResult Index()
    {
            return View();
    }
}

Change the configure method in startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
     if (env.IsDevelopment())
      {
         app.UseDeveloperExceptionPage();
      }

      app.UseDefaultFiles();
      app.UseStaticFiles();
      app.UseMvc();

}

Now after these changes if I deploy the app in local IIS it works fine and load the default View Home/Index when I access it the URL localhost:801

But If I deploy it on linux it gives a 503 error and there are different errors in the log too

Microsoft.AspNetCore.Routing.Tree.TreeRouter[1] Request successfully matched the route with name '(null)' and template ''.

Microsoft.AspNetCore.Mvc.Versioning.ApiVersionActionSelector[2] Action 'UMD.VAST.WebAPI.Controllers.HomeController.Index (UMD.VAST.WebAPI)' with id 'b83c6143-cd71-4847-90e8-14a963a8ce31' did not match the constraint

'Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint' Microsoft.AspNetCore.Mvc.Internal.MvcAttributeRouteHandler[3] No actions matched the current request. Route values: Microsoft.AspNetCore.Builder.RouterMiddleware[1] Request did not match any routes. Microsoft.AspNetCore.Mvc.Routing.DefaultApiVersionRoutePolicy[5] Multiple candidate actions were found, but none matched the requested service API version '1.0'. Candidate actions: UMD.VAST.WebAPI.Controllers.HomeController.Index (UMD.VAST.WebAPI) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0] An unhandled exception has occurred while executing the request System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(HttpRequest request) at Microsoft.AspNetCore.Mvc.Routing.DefaultApiVersionRoutePolicy.ClientError(RouteContext context, ActionSelectionResult selectionResult)

Upvotes: 2

Views: 4099

Answers (1)

Nouman Bhatti
Nouman Bhatti

Reputation: 1421

I don't know why it doesn't work with Web API Controller, but I fixed it by using the MVC Controller for the Index page. Rest of the controller are Web Api controllers.

Code in Configure method for MVC routes is

 app.UseMvc(routes =>
  {
      //Home
      routes.MapRoute(
         name: "home",
         template: "{controller}/{action}/{id?}",
         defaults: new { controller = "Home", action = "Index" });
  });

For Web Api controllers I'm using the attribute routing

Upvotes: 1

Related Questions