我的问题是405(方法不允许),但我没有解决我的问题 问题出在哪儿?为什么我不能在没有参数的情况下发帖?
javascript代码在这里
<script type="text/javascript">
$(document).ready(function () {
var getResult = GetData();
console.log("GetData => " + getResult);
var getResult2 = PostDataURLParamater();
console.log("PostDataURLParamater => " + getResult2);
var getResult3 = PostData();
console.log("PostData => " + getResult3);
})
function GetData() {
var result;
$.ajax({
url: "http://localhost:64073/api/home/helloworld",
type: "GET",
datatype: "JSON",
async: false,
success: function (data) {
result = data;
},
error: function (msg) {
console.log("Error: " + msg);
}
});
return result;
};
function PostDataURLParamater() {
var result;
$.ajax({
url: "http://localhost:64073/api/home/HelloWorldForPost?name=MustafaParamater",
type: "POST",
datatype: "JSON",
async: false,
success: function (data) {
result = data;
},
error: function (msg) {
console.log("Error: " + msg);
}
});
return result;
}
function PostData() {
var result;
var data = JSON.stringify({ name: "Mustafa" });
$.ajax({
type: 'POST',
url: 'http://localhost:64073/api/home/HelloWorldForPost',
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
result = data;
},
error: function (msg) {
console.log("Error: ", msg);
}
});
return result;
}
</script>
和全球的asax就在这里
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
}
}
和web api在这里
public class HomeController : ApiController
{
public const string fv = "Hello Wold!";
[HttpGet]
public string HelloWorld()
{
return fv;
}
[HttpPost]
public string HelloWorldForPost(string name)
{
return string.IsNullOrEmpty(name) ? fv : (fv + " by " + name);
}
}
和chrome控制台就在这里 Chrome Console
答案 0 :(得分:0)
使用帖子参数有一些警告。
这是我找到的最好的资源:
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
最有可能:
// POST api/values
public string Post([FromBody]string value) {
return value;
}
这很古怪:
$.post('api/values', { '': value });