我在WebAPI应用程序中有一个相当长的路由
[HttpPost]
[Route("api/machines/{machineId}/measurements/scopes")]
public IHttpActionResult SaveScopeForMachine(int machineId, [FromBody]ScopeViewModel scopeVM, int? userId, int? locationId)
{
在尝试发布数据时,我总是得到404
。要发布数据,我使用MATLAB
options = weboptions('MediaType','application/json', 'RequestMethod', 'post');
webwrite('http://localhost:62284/api/machines/1/measurements/scopes', data, options)
另一种Post方法可以正常工作,例如这一个
[HttpPost]
[Route("api/systems/{id}/machine/")]
public IHttpActionResult AddMachineFromSystem(int id, [FromBody]MachineViewModel machineVM)
即使我在这里试试这个也很有效
[HttpPost]
[Route("api/mytest")]
public IHttpActionResult mytest([FromBody]ScopeViewModel svm)
{
SaveScopeForMachine(1, svm, null, null);
return Ok();
}
其他信息:我有webapi和mvc
我在webapi中的路由(可能太过载了?)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApiOverview",
routeTemplate: "api/{controller}/",
defaults: null
);
config.Routes.MapHttpRoute(
name: "DefaultApiWithoutId",
routeTemplate: "api/{controller}/{action}/",
defaults: null
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
我的应用程序从global.asax开始(是的,我首先定义了webapiconfig)
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
答案 0 :(得分:1)
如果没有再看到你的代码,我想你可能认为params是可选的,但它们是nullable
。
试试这个
[HttpPost]
[Route("api/machines/{machineId}/measurements/scopes")]
public IHttpActionResult SaveScopeForMachine(int machineId, [FromBody]ScopeViewModel scopeVM, int? userId = null, int? locationId = null)
您之前的路线仍然需要它们存在,这样它们会被赋予一个值,因此可以省略它们。