C#HttpClient返回错误404未找到

时间:2016-03-05 00:51:38

标签: c# http-post dotnet-httpclient

花了好几个小时试图解决这个问题。响应消息始终具有404 Not found错误。任何帮助将不胜感激!

public static class BackendlessAPIHelper
{
    internal static string appId = "my-app-id";
    internal static string restSecret = "my-api-secret";
    internal static string backendlessBase = "https://api.backendless.com/";
    internal static string signupUrl = "v1/user/register";

    public static async Task<bool> UserSignup(string username, string password)
    {
        bool signupsuccessful = false;
        var client = new HttpClient();
        UserSignupBackendless newuser = new UserSignupBackendless { email = username, password = password };
        string newuserjson = JsonConvert.SerializeObject(newuser);

        try
        {
            client.BaseAddress = new Uri(backendlessBase);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("application-id", BackendlessAPIHelper.appId);
            client.DefaultRequestHeaders.Add("secret-key", BackendlessAPIHelper.restSecret);
            client.DefaultRequestHeaders.Add("application-type", "REST");
            StringContent theContent = new StringContent(newuserjson, System.Text.Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(backendlessBase+signupUrl, theContent);
            if (response.IsSuccessStatusCode)
            {
                signupsuccessful = true;
                return signupsuccessful;
            }
            else
                return signupsuccessful;
        }
        catch(Exception ex)
        {
            ex.ToString();
            return signupsuccessful;
        }
    }
}

以下是API文档:https://backendless.com/documentation/users/rest/users_user_registration.htm

我按照这里的文章:http://blogs.msdn.com/b/wsdevsol/archive/2013/02/05/how-to-use-httpclient-to-post-json-data.aspx

更新:我意识到了这个错误。注册URL不正确(错过了一个字符)。

1 个答案:

答案 0 :(得分:2)

我认为您的基本网址正在重复:

client.BaseAddress = new Uri(backendlessBase);
// ...
HttpResponseMessage response = await client.PostAsync(backendlessBase+signupUrl, theContent);

您要两次指定backendlessBase。如果您已使用BaseAddress指定了基础,请不要在通话中再次指定。

另外,如果您仔细阅读文档,则users/register,而不是user/register