gpt4 book ai didi

c# - 如何在路由中定义 PUT 方法只限于 Controller 中的 Put 方法不带参数?

转载 作者:可可西里 更新时间:2023-11-01 08:59:32 26 4
gpt4 key购买 nike

这里是WebApiConfig.cs中的路由配置:

config.Routes.MapHttpRoute(
name: "DefaultApiPut",
routeTemplate: "api/{controller}",
defaults: new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) }
);


config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get, HttpMethod.Post, HttpMethod.Delete) }
);

这是我的 Controller :

public class MyController : ApiController {
[HttpPut]
public void Put()
{
//blah
}
}

不知何故,当客户端发送带有 URL /api/myController/12345 的 PUT 请求时,它仍然映射到 MyController 中的 Put 方法>,我预计会出现类似资源未找到的错误。

如何强制Put方法只接受不带参数的请求?

提前致谢!

最佳答案

这可以限制路由上的 http 方法:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "LocationApiPOST",
routeTemplate: "api/{orgname}/{fleetname}/vehicle/location",
defaults: new { controller = "location" }
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }
);

config.Routes.MapHttpRoute(
name: "LocationApiGET",
routeTemplate: "api/{orgname}/{fleetname}/{vehiclename}/location/{start}",
defaults: new { controller = "location", start = RouteParameter.Optional }
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);

...

}

关于c# - 如何在路由中定义 PUT 方法只限于 Controller 中的 Put 方法不带参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12609759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com