Unified MVC Controller Routing in Asp.Net 5

While working in ASP.NET 5, I am confused by some concepts of unified controllers. Please show me what I'm doing wrong.

In ASP.NET 5, the same controller is used for MVC and WebApi, with the only difference being the Routing attribute defined above the Web Api controller. My thoughts are that the Route attribute is only used to define a route. But there were some events that defined the Route attribute at the top, specifying the controller as the Web Api controller.

In Startup.cs, I have the following routing configurations.

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

            routes.MapWebApiRoute(
                "DefaultApi",
                "api/{controller}/{id?}");
        });

There is an "HttpGet" action in the Home Controller to accept a WebApi request get, but it cannot be called without the "Route" attribute, however, the routing for the web api is already defined in the launch class.

public class HomeController : Controller {
    public IActionResult Index() {
        return View();
    }

    //[Route("api/[controller]")]
    [HttpGet]
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }
}

And in the "Values" controller, the "About" action is not available, since calling "/ values ​​/ about" will lead to an error not found. And "/ api / values ​​/ about" will be redirected to the "Get" action.

[Route("api/[controller]")]
public class ValuesController : Controller {
    public IActionResult About() {
        ViewData["Message"] = "Your application description page.";

        return View();
    }

    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }
}

But although I specified the web api route in the startup.cs file, I cannot access the path "/ api / home". What am I doing wrong?

+4
source share
1 answer

I believe that you are mixing different routing methods.

, webapi MVC.

MapWebApiRoute , WebApi 2 ASP.NET.

, UseMvc , :

app.UseMvc();

. : ASP.NET 5 Deep Dive: .

. MVC WebApi ASP.NET 5.

0

Source: https://habr.com/ru/post/1606289/


All Articles