c# - 更改 WebAPI 中的默认路由

标签 c# asp.net asp.net-web-api

是新手,正在从 ruby​​ on Rails 过渡。我想了解如何更改默认路由以使用自定义路由。

例如,我的 WebApiConfig.cs 中的当前路由如下:

config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional}

所以我在 Controller 中配置的 URL GET api 是:

https://localhost:44300/api/Controller?type=FirstType

我的 Controller 中定义的相应方法是:

public HttpResponseMessage GetControllerByType(string type)

使用URL调用WEB api时需要进行哪些更改才能执行与上面相同的操作:

https://localhost:44300/api/Controller/FirstType

最佳答案

假设您使用的是 WebAPI 2,您可以使用 Controller 内操作的属性来创建自定义路由。

将以下内容添加到 WebApiConfig.cs 的 Register 方法中:

config.MapHttpAttributeRoutes();

以上内容应添加在您上面已发布的默认路由配置之前。

然后在 Controller 中,您可以使用注释来描述路由:

[Route("controller/{type}")]
[HttpGet]
public HttpResponseMessage GetControllerByType(string type)

括号内的值表示通过名称绑定(bind)到方法参数的变量。

您还可以对类本身进行注释,使其具有适用于该 Controller 中所有方法的前缀:

[RoutePrefix("stuff")]
public class MyController : ApiController
{
    [Route("myAction/{id}")] //route to this is via /stuff/myAction/{id}
    [HttpGet]
    public HttpResponseMessage MyMethod(string id)  
    { ... }
}

唯一的“问题”是查询字符串不应该位于路由模板内,这些字符串由方法签名中的可选参数(具有默认值的参数)表示,这些参数在路由模板内也没有可选注释字符串。 (即:"myAction/{id:string?}" 必须在签名中具有默认值,但所有其他不具有默认值的 id 参数都可以通过查询字符串分配)

任何未提供使用注释的路由模板的内容都将回退到使用 WebApiConfig 中指定的默认路由,默认情况下为“/api/controller_name/action_name/”

这里有一个关于使用您可以设置的属性的所有自定义路由的精彩教程:Attribute Routing in ASP.NET WebAPI 2

关于c# - 更改 WebAPI 中的默认路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620015/

相关文章:

c# - 将自定义搜索过滤器转换为动态 SQL

c# - 如何提示一个新窗口显示所选项目的模型数据?

c# - 帮助理解 Enumerable.Join 方法

asp.net - 使用 System.Web.ApplicationServices.AuthenticationService 进行 WCF 服务身份验证,我无法向成员资格提供程序进行身份验证

c# - WebApi 中的 Hangfire 与 Autofac : Job not running

c# - WCF 和 Web API 的区别总结

c# - C# 中的 Cast 删除实现的成员数组

c# - 系统.InvalidOperationException : The model item passed into the dictionary is of type

jquery - visual studio 2010 jquery 和 ScriptManager 导致错误

c# - 大数据量的 Web API 中的 502 错误