Web服务的C#Web API路由 [英] C# web api route for a webservice

查看:587
本文介绍了Web服务的C#Web API路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#编写Web api,并且我对访问名为test的函数的正确路径有疑问.

I am coding a web api in c# and I have a question in regards to the correct route to access a function called test.

这是类的定义:

[RoutePrefix("api")]
public class ItemsWebApiController : ApiController

我有一个RoutePrefix,如下:

[Route("test")]

这是名为test的函数:

[Route("test")]
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
public String test()
{
    return "test";
}

我正在尝试访问以下网址: http://localhost/api/test

I am trying to access the following url: http://localhost/api/test

上面的网址显示以下异常:

The above url is displaying the following exception:

"/"应用程序中的服务器错误.

Server Error in '/' Application.

找不到资源.

说明:HTTP404.您要查找的资源(或其资源之一) 依赖项)可能已被删除,名称已更改,或者是 暂时不可用.请查看以下网址并进行 确保其拼写正确.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

请求的URL:/api/test

Requested URL: /api/test

如何访问test函数,以便在浏览器中显示字符串"test"?

How can I access the test function, such that the string "test" is displayed in my browser?

编辑

我已部署到本地IIS,并且数据库连接字符串正常工作.

I have deployed to my local IIS, and the database connection strings are working correctly.

本地IIS的地址为 http://localhost/

这些是我尝试过的网址:

These are the urls that I have tried:

http://localhost/test

http://localhost/api/test

http://localhost/api/test/test

http://localhost/ItemsWebApiController/test

http://localhost/ItemsWebApi/test

以上所有内容均返回错误页面.

All of the above return the error page.

谢谢

推荐答案

您必须在WebAPI控制器中激活属性路由

You have to activate Attribute Routing in WebAPI Controllers

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 }
        );
    }
}

并在您的应用程序中启动

and in your application start

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

然后您的URL为http://localhost/test,因为此处的默认路由不匹配.

And then your URL is http://localhost/test, because the default route would not match here.

这篇关于Web服务的C#Web API路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆