您好我在向webAPi操作方法执行ajax发布时遇到了问题但是我收到了错误:
下面是我的ajax电话:{" Message":"未找到与请求URI匹配的HTTP资源 ..."," MessageDetail":"控制器上未找到任何操作 匹配请求。"}
$.ajax({
url: "http://localhost/SomeService/api/ControllerName/TestPostMethod",
type: "POST",
data: JSON.stringify({ userId: "testuser', loc: "test" }),
contentType: "application/json;charset=utf-8",
success: function (msg) {
returnVal = msg;
},
error: function (xhr, msg) {
var response = JSON.parse(xhr.responseText);
if (xhr.readyState == 4) {
if (xhr.status != 401) {
if (response.Message) {
console.log(response.Message);
}
}
} else {
if (response.Message) {
console.log(response.Message);
}
}
}
});
以下是我的webApi方法:
[System.Web.Http.HttpPost()]
public HttpResponseMessage TestPostMethod([FromUri]string userId, string loc)
{
return Request.CreateResponse<string>(HttpStatusCode.OK, "success");
}
这是路由的配置方式:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints:null
);
答案 0 :(得分:0)
解决此问题的最简单方法(可能还有其他方法)是定义UserLocation等自定义对象 -
public class UserLocation
{
public string userId { get; set; }
public string loc { get; set; }
}
执行此操作后,将TestPostMethod方法的参数更新为([FromBody] UserLocation userLocation)
假设该方法存在于名为&#34; ControllerName&#34;的控制器中。现在应该可以使用(并且您可以从对象访问两个值)