简体   繁体   中英

How do I set up basic routing for .NET WEBAPI?

I'm trying to learn .NET Web API so I decided to follow this very simple introduction:

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

However, I can't even get this working. I copied and pasted code directly to make sure I wasn't making some mistake, but when I run it, trying to access a path such as api/products/2 returns a 404.

Looking at my project, I didn't see any method of routing a path to the controller. The only thing relevant in Web.config is:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

I had no WebApiConfig.cs, which seems to be required, so after some searching, I came up with this, which seems to be something of a default:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(config =>
        {
            config.MapHttpAttributeRoutes();

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

That doesn't seem to work either. Currently I just that WebApiConfig.cs and the code described in the guide I linked above. Does anybody know what else I might be missing?

Note: I'm using Visual Studio Community. I think the professional versions may help with wiring this stuff up, but I'm going to have to do it manually.

Edit: Adding full code:

Product.cs

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

ProductControllers.cs

public class ProductController : ApiController
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[] 
    { 
        new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
    };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }
}

The way you registering the route is not standard.

Here is the command way of registering route. The reason is you will be registrating filters same way later.

Global.asax

public class WebApiApplication : HttpApplication
{
   protected void Application_Start()
   {
      GlobalConfiguration.Configure(WebApiConfig.Register);
      // RouteConfig.RegisterRoutes(RouteTable.Routes);
      // FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   }
}

WebApiConfig.cs

public static class WebApiConfig
{
   public static void Register(HttpConfiguration config)
   {
      config.MapHttpAttributeRoutes();

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

So I got it working:

Created global.aspx with:

<script runat="server">
    void Application_Start(object sender, EventArgs e) 
    {
        WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
    }
</script>

Changed WebApiConfig.cs to:

using System.Web.Http;

public class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });
    }
}

Works fine now. I just had to figure out how to register the routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM