1

I have an ASP.NET Webforms web site that includes Web API. The site is developed and tested with Visual Studio 2013 and .NET 4.5 on Windows 8 with IIS Express as web server.

I have added the Web Api controller in the root directory that is defined as follows:

[RoutePrefix("api")]
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 } 
    };
    [Route("ProductsController")]
    [HttpGet]
    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }

    public Product GetProductById(int id)
    {
        var product = products.FirstOrDefault((p) => p.Id == id);
        if (product == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return product;
    }

    public IEnumerable<Product> GetProductsByCategory(string category)
    {
        return products.Where(
            (p) => string.Equals(p.Category, category,
                StringComparison.OrdinalIgnoreCase));
    }
}

The Global.asax looks like this:

public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);


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

    }
}

I have included these 2 lines in my web.config file

<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>

When I make the get request with the following Url : http://localhost:5958/api/products, I get HTTP Error 404.0. I have tried different solutions but nothing works. Is there something that I'm missing? How do I rectify this problem?

Thanks in advance.

2 Answers 2

2

You mixing up some of your convention-based and attribute routing for your web api.

Attribute Routing in ASP.NET Web API 2

If you are going to use attribute routing then you need to properly add the routes to your controller.

[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
    //...code removed for brevity

    //eg: GET /api/products
    [HttpGet]
    [Route("")]
    public IEnumerable<Product> GetAllProducts(){...}

    //eg: GET /api/products/2
    [HttpGet]
    [Route("{id:int}")]
    public Product GetProductById(int id){...}

    //eg: GET /api/products/categories/Toys
    [HttpGet]
    [Route("categories/{category}")]
    public IEnumerable<Product> GetProductsByCategory(string category){...}
}

Now that you have your routes properly defined, you need to enable attribute routing.

WebApiConfig.cs

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {

        // Enable attribute routing
        config.MapHttpAttributeRoutes();

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

make sure to update the Global.asax code to the following:

public class Global : HttpApplication {
    void Application_Start(object sender, EventArgs e) {
        //ASP.NET WEB API CONFIG
        // Pass a delegate to the Configure method.
        GlobalConfiguration.Configure(WebApiConfig.Register);

        // Code that runs on application startup
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

WebForm's RouteConfig

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }
}

resource:

Can you use the attribute-based routing of WebApi 2 with WebForms?.

Sign up to request clarification or add additional context in comments.

5 Comments

Where should I add the controller class?
Doesn't really matter. Most people just create a folder called Controllers and place them there. Once the class is included in the project
It didn't work. I added all the attributes and updated the global.asax file. I created a new webforms project with Web api enabled. Web api controller works fine there. I'm thinking about copying all the files from tis project to that one.
You could do that as well. I see nothing wrong with that. I would suggest you look at the differences in the new project to your current one so you get an understanding as to what may be causing your issue. Happy coding.
take a look at the following answer to Can you use the attribute-based routing of WebApi 2 with WebForms?. I've updated my answer to include the additional info.
0

Based on your code,you didn't include routes for webapi. If you install Webapi from Nuget, you can find the WebApiConfig file under App_Start which contains the Route configuration for WebApi. If not create a new route config file for webapi

using System.Web.Http;
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

Use this static method in your Global.ascx.

using System.Web.Http;
 void Application_Start(object sender, EventArgs e)
    {

        GlobalConfiguration.Configure(WebApiConfig.Register);
        // Code that runs on application startup
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

1 Comment

I did all of that, still the same issue. Do I need to change anything in web.config?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.