Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net web api WebApi POST无法通过ajax调用工作_Asp.net Web Api_Http Post - Fatal编程技术网

Asp.net web api WebApi POST无法通过ajax调用工作

Asp.net web api WebApi POST无法通过ajax调用工作,asp.net-web-api,http-post,Asp.net Web Api,Http Post,您好,我在执行ajax post to webAPi操作方法时遇到问题,但是我遇到了错误: {“Message”:“未找到与请求URI匹配的HTTP资源 …”,“MessageDetail”:“在 与请求匹配。“} 下面是我的ajax调用: $.ajax({ url: "http://localhost/SomeService/api/ControllerName/TestPostMethod", type: "PO

您好,我在执行ajax post to webAPi操作方法时遇到问题,但是我遇到了错误:

{“Message”:“未找到与请求URI匹配的HTTP资源 …”,“MessageDetail”:“在 与请求匹配。“}

下面是我的ajax调用:

$.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");
        }
解决此问题的最简单方法(可能还有其他方法)是定义自定义对象,如UserLocation-

public class UserLocation 
{
    public string userId { get; set; }
    public string loc { get; set; }
}
完成此操作后,将TestPostMethod方法的参数更新为([FromBody]UserLocation UserLocation)


假设该方法存在于名为“ControllerName”的控制器中,现在应该可以工作了(您可以从对象访问两个值)

在这里找到了我的答案:您需要通过在
TestPostMethod
方法中定义模型来发送数据。我看到您在发布后回答了自己的问题,无论是哪种方式-上述方法都应该可以工作:)
public class UserLocation 
{
    public string userId { get; set; }
    public string loc { get; set; }
}