当本地主机:端口号在iis-express中的浏览器地址中时,webapi显示403.14错误
本文关键字:地址 webapi 显示 错误 浏览器 主机 口号 iis-express | 更新日期: 2023-09-27 17:58:34
这一定很愚蠢,但我想不出还能做什么。
使用Visual Studio 2013-Update 1,我在现有的解决方案中创建了一个空的web api 2项目,添加了跨源支持(cors)包,并创建了基本的web api控制器。
WebApiConfig类似乎很好:
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 }
);
}
还有Global.asax
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
然后我运行应用程序,IIS express正常启动,浏览器以应用程序的url启动,但似乎什么都不起作用。
如果URL是"localhost:port number",我会得到HTTP错误403.14-禁止Web服务器配置为不列出此目录的内容。
如果我尝试"localhost:port-number/api",我会得到HTTP错误404.0-未找到您要查找的资源已被删除、名称已更改或暂时不可用
我看了几个博客、教程和例子,但没有看到任何特别需要做的事情。有人能告诉我我可能错过了什么吗?
WebApi没有默认的可查看页面(aspx、html等),可以通过导航到根目录(本例中为localhost:port
)进行查看。所以这是正常的行为。为了通过控制器访问Api,您需要使用MapHttpRoute()
方法中指定的路由模板来访问它。
因此,要访问Api中的GET
方法,您需要打开浏览器并将localhost:port/api/{controllername}
放入url中。{controllername}
将被设置为控制器类的名称,而不会在末尾添加controller。
例如:如果你的控制器是这样的:
public class TestController : ApiController {
public HttpResponseMessage Get() {
return something;
}
public HttpResponseMessage Get(int id) {
return something with id;
}
}
那么你的第一个Get()
的url看起来是这样的:
localhost:port/api/test
第二个Get(int id)
的url如下所示:
localhost:port/api/test/5
如果你的路由配置确实可以,你可以尝试在Web.config中添加它:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>