未找到 WebApi POST 方法但 GET 有效

WebApi POST method not found but GET works

我今天试了很多次用POST调用网络api函数(HttpClient.PostAsync) 方法。但不幸的是我不能。 只有使用 GET (HttpClient.GetAsync) 方法的调用才能成功。 我尝试在网上跟踪许多示例,但总是出现相同的错误。 ("Not Found")

如果有人能帮助我,非常感谢

这是 C# Web API:

[RoutePrefix("NewAreaMap")]
public class NewAreaMapController: ApiController
{
    [HttpPost]
    [ActionName("PostCreateAreaTemp")]
    public AreaTemp PostCreateAreaTemp(double southLatitude, double westLongitude, double northLatitude, double eastLongitude, int countryId, int worldId)
    {
        AreaTemp newTempMap = new AreaTemp();
        //.....
        * * Here is the C# code from client side: * *
            using(var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["SrvWebApiPath"].ToString());
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var values = new Dictionary < string,
                    string > ()
                    {
                        {
                            "southLatitude", southLatitude.ToString()
                        },
                        {
                            "westLongitude", westLongitude.ToString()
                        },
                        {
                            "northLatitude", northLatitude.ToString()
                        },
                        {
                            "eastLongitude", eastLongitude.ToString()
                        },
                        {
                            "countryId", countryId.ToString()
                        },
                        {
                            "worldId", worldId.ToString()
                        }
                    };
                var content = new FormUrlEncodedContent(values);
                HttpResponseMessage response = await client.PostAsync("api/NewAreaMap/PostCreateAreaTemp", content)
                if (response.IsSuccessStatusCode)
                {
                    string jsonData = response.Content.ReadAsStringAsync().Result;
                    newAreTemp = JsonConvert.DeserializeObject < AreaTemp > (jsonData);
                }
        }

GET 调用适用于以下 Url:

HttpResponseMessage response = await client.GetAsync("api/NewAreaMap/GetAreaTemp/?latitudeAreaCenter=7.02&longitudeAreaCenter=9.05");

请尝试将 FromBody 属性与您的操作参数一起使用。

replace your method parameter with object because you are passing full object "content" from the httpclient so in that case you need to use same object here also with [frombody] attribute methodname([FromBody] Content content) define all the properties in one class and use . Hope it will helpful for you.

既然您要发布 JSON,您不妨将其作为对象发送。或者,如果您仍想保留字典和方法的签名,您可以尝试:

var content = new StringContent(JsonConvert.SerializeObject(values),
            Encoding.UTF8, "application/json");

而不是

var content = new FormUrlEncodedContent(values);

这是一个对象示例。

public class SampleObject
{
    public double SouthLatitude { get;  set; }
    public double WestLongitude { get; set; }
    public double NorthLatitude { get; set; }
    public double EastLongitude { get; set; }
    public int CountryId { get; set; }
    public int WorldId { get; set; }
}

并更改您的要求。

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(ConfigurationManager.AppSettings["SrvWebApiPath"].ToString());
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var obj = new SampleObject
    {
        SouthLatitude = southLatitude,
        WestLongitude = westLongitude,
        NorthLatitude = northLatitude,
        EastLongitude = eastLongitude,
        CountryId = countryId,
        WorldId = worldId
    };

    // Send it as StringContent.
    var request = new StringContent(JsonConvert.SerializeObject(obj),
        Encoding.UTF8, "application/json");

    HttpResponseMessage response = await client.PostAsync("api/NewAreaMap/PostCreateAreaTemp", request)
    if (response.IsSuccessStatusCode)
    {
        string jsonData = response.Content.ReadAsStringAsync().Result;
        newAreTemp = JsonConvert.DeserializeObject<AreaTemp>(jsonData);
    }
}

以及服务器上的签名。

public AreaTemp PostCreateAreaTemp(SampleObject sampleObject)

或者如果需要:

public AreaTemp PostCreateAreaTemp([FromBody]SampleObject sampleObject)