在 MVC 中发布发布参数 API
Issue posting parameter in MVC API
我在网站上有一个 Web API。如果 api 调用中没有参数,那么我可以命中它,但是如果它上面有参数,那么我就不能命中它。下面是我正在谈论的例子。
[HttpGet]
public string GetFacilityName2()
{
return "Good";
}
[HttpGet]
public string GetFacilityName(string projectNumber)
{
return "Never Get Here";
}
此时我的配置路由是默认的。
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我正在使用以下两个网址。 Url 有效的是 http://localhost/api/Controller/GetFacilityName2
Url 不起作用的是 http://localhost/api/Controller/GetFacilityName?projectNumber=44
更新
我在 API 上有第三种方法,就是这样。
[HttpGet]
public Address GetWorkplaceAddress(string projectNumber)
{
return new Address();
}
当我从 API 中删除它时,另一种方法开始起作用。地址是这样定义的。
public class Address
{
public int Id { get; set; }
public string AddressValue { get; set; }
public string City { get; set; }
public int? State { get; set; }
public string Zip { get; set; }
public int? Country { get; set; }
}
您不能通过参数重载控制器上的操作,这是您当前编写代码的方式。
您可以使用
按名称指定要执行的操作
-
RouteAttribute
- 路线模板
routeTemplate: "api/{controller}/{action}/{id}",
或您可以通过当前正在执行的 Http 动词(Get、Post、Put 等)指定它。
我在网站上有一个 Web API。如果 api 调用中没有参数,那么我可以命中它,但是如果它上面有参数,那么我就不能命中它。下面是我正在谈论的例子。
[HttpGet]
public string GetFacilityName2()
{
return "Good";
}
[HttpGet]
public string GetFacilityName(string projectNumber)
{
return "Never Get Here";
}
此时我的配置路由是默认的。
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我正在使用以下两个网址。 Url 有效的是 http://localhost/api/Controller/GetFacilityName2
Url 不起作用的是 http://localhost/api/Controller/GetFacilityName?projectNumber=44
更新 我在 API 上有第三种方法,就是这样。
[HttpGet]
public Address GetWorkplaceAddress(string projectNumber)
{
return new Address();
}
当我从 API 中删除它时,另一种方法开始起作用。地址是这样定义的。
public class Address
{
public int Id { get; set; }
public string AddressValue { get; set; }
public string City { get; set; }
public int? State { get; set; }
public string Zip { get; set; }
public int? Country { get; set; }
}
您不能通过参数重载控制器上的操作,这是您当前编写代码的方式。
您可以使用
按名称指定要执行的操作-
RouteAttribute
- 路线模板
routeTemplate: "api/{controller}/{action}/{id}",
或您可以通过当前正在执行的 Http 动词(Get、Post、Put 等)指定它。