質問

This has to be something really dumb but I can't think what else to do.

Using Visual Studio 2013 - Update 1, I created an empty web api 2 project in an existing solution, added the cross origin support (cors) package and created a basic web api controller.

The WebApiConfig class seems to be fine:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var cors = new EnableCorsAttribute("*","*","*");
        config.EnableCors(cors);
        // Web API routes
        config.MapHttpAttributeRoutes();

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

And also the Global.asax

    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

I then run the application, IIS express starts normally and the browser starts with the application's url but nothing seems to work.

If the URL is "localhost:port number" I get HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

If I try "localhost:port number/api" I get HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

I have looked at several blogs, tutorials, examples and I haven't seen anywhere that anything special needs to be done. Could someone please shed some light in what I might be missing?

役に立ちましたか?

解決

Web Api doesn't have a default viewable page (aspx, html, etc) that can be viewed by navigating to the root (localhost:port in this case). So that is the normal behavior. In order to access your Api through the controller you need to access it using the route template specified in your MapHttpRoute() method.

So to access the GET method in your Api you would open a browser and place localhost:port/api/{controllername} into the url. {controllername} would be set to the name of your controller class without Controller added to the end.

ex: If your controller looked like this:

public class TestController : ApiController {
    public HttpResponseMessage Get() {
          return something;
    }

    public HttpResponseMessage Get(int id) {
          return something with id;
    } 
}

Then your url for the first Get() would look like this:

localhost:port/api/test

And the url for the second Get(int id) would look like this:

localhost:port/api/test/5

他のヒント

If yours route config is OK for sure, you can try add this in Web.config:

<system.webServer>
 <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top