Web APi Routing Understanding

2019-09-06 09:25发布

问题:

I have created a new controller called WebPortalController but when I call it or try to call it via the browser I couldnt access the below method just said resource is not found. Do I need to add a new routing to the RoutesConfig.cs code if so how.?

namespace WebApi.Controllers
{
public class WebPortalController : ApiController
{
    // GET api/webportal
    private WebPortEnterpriseManagementDa _da = new WebPortEnterpriseManagementDa();


    public ManagedType Get(string name)
    {

        ManagedType items = _da.GetManagedType(name);

        return items;
    }


    // POST api/webportal
    public void Post([FromBody]string value)
    {
    }

    // PUT api/webportal/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/webportal/5
    public void Delete(int id)
    {
    }
}
}

Routes file

namespace WebApi
{
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );


    }
}

回答1:

The route config you have shown is for MVC routes and is located in the App_Start/RouteConfig file. Check that you have a default API route set in your App_Start/WebApiConfig:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional } 
);

Then you will need to change the parameter name in your Get method to match the routing parameter:

public ManagedType Get(string id)
{
    ManagedType items = _da.GetManagedType(name);
    return items;
}

This should allow you to call your Get method through a browser using:

localhost:55304/api/WebPortal/Test

In order to test out your Post/Put/Delete methods you will need to use Fiddler or a browser addin such as Postman