我只能使用ajax调用asp GET方法。 这是我的JavaScript:
$scope.test = function () {
var dataObject = {};
dataObject.Company_Code = companyCode;
$http({
method: 'POST',
url: 'http://localhost:31041/api/Location/test',
data: $.param(dataObject),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + token
}
})
.success(function (data) {
}).error(function () {
});
}
这是我的WebAPI方法:
[HttpPost]
public string test(Company_Details Company)
{
return "11";
}
我的global.asax
设置:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept,Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
当我尝试调用此方法时,收到以下错误:
我也可以使用URL参数调用post方法(url: 'http://localhost:31041/api/Location/test?Name:123',
)。但无法使用data: $.param(dataObject)
答案 0 :(得分:1)
尝试将[FromBody]
添加到Company_Detailss
参数:
[HttpPost]
public string test([FromBody]Company_Details Company)
{
return "11";
}
答案 1 :(得分:0)
试试这个
[RoutePrefix("api/Location")]
[HttpPost]
[Route("test")]
public string test(Company_Details Company)
{
return "11";
}
答案 2 :(得分:0)
看起来您需要使用 JSON.stringify 作为您的数据对象
method: 'POST',
url: 'http://localhost:31041/api/Location/test',
data: JSON.stringify($.param(dataObject))