Xamarin.Forms HTTP发布到Web服务 - 404错误

时间:2017-07-20 14:47:58

标签: c# web-services asp.net-web-api xamarin.ios xamarin.forms

很抱歉,如果已经提出这个问题,但我似乎找不到与我的问题相关的问题。我有一个使用C#Asp.Net Web API构建的Web服务,这里我有以下POST方法:

    [HttpPost]
    [Route("AddLocation")]
    public void PostLocation(Locations model)
    {
        using (Entities db = new Entities())
        {
            C_btblFALocation newLocation = new C_btblFALocation()
            {
                cLocationCode = model.Code,
                cLocationDesc = model.Description
            };

            db.C_btblFALocation.Add(newLocation);
            db.SaveChanges();
        }
    }

在我的Xamarin.Forms项目中,我有我的Rest服务类:

    public async Task SaveLocationAsync(Locations item)
    {
        var uri = new Uri(string.Format(Constants.LocationSaveRestUrl));

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

            HttpResponseMessage response = null;
            response = await client.PostAsync(uri, content);

            if (response.IsSuccessStatusCode)
            {
                Debug.WriteLine(@"             Location successfully added.");
            }
            else
            {
                Debug.WriteLine(@"             Oops, there seems to be a problem.");
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(@"             ERROR {0}", ex.Message);
        }
    }

我的网址是在我的常量类中设置的:

public static string LocationSaveRestUrl = "http://172.16.124.18/ArceusService/api/Assets/AddLocation/";

问题是我一直收到404错误。我已经尝试过各种方式来设置URL,但没有运气。数据似乎从调试中得到了很好的通过,但我不知道URL应该如何用于POST方法?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的client变量是如何声明的?通常您设置BaseAddress并在Get/PostAsync中设置实际资源URI。

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}