Xamarin csrf-token使用HttpClient

时间:2017-01-03 21:18:27

标签: c# xamarin csrf dotnet-httpclient

我正在尝试使用我的Xamarin应用运行一个帖子请求。我的后端是一个允许所有交叉起源的Django应用程序:

CORS_ORIGIN_ALLOW_ALL = True

当我尝试使用我的Angular2应用程序POST,PUT,GET,PATCH,DELETE时没有问题,但是当我尝试使用我的Xamarin应用程序时,我的后端会返回此错误:

csrf token missing or incorrect

我的Xamarin c#代码看起来像这样:

namespace Services
{
    public static class Authentication
    {
        public static async Task<string> Login(string email, string password)
        {
            var loginModel = new LoginModel() { email = email, password = password };
            Uri uri = new Uri(Environment.server_url + "rest-auth/login/");
            var json = JsonConvert.SerializeObject(loginModel);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;
            using (var client = new HttpClient())
            {
                response = await client.PostAsync(uri, content);
            }
            return await response.Content.ReadAsStringAsync();
        }
    }

    public class LoginModel
    {
        public LoginModel()
        {
        }
        public string email;
        public string password;

    }
}

如您所见,标题中没有添加csrf-token,因为不知道如何使用Xamarin获取此标记。

我尝试了一些像这样的随机代码:

client.DefaultRequestHeaders.Add("x-csrf-token", "Fetch");

或者这个,用随机令牌来看:

client.DefaultRequestHeaders.Add("x-csrf-token", "IYTN3eZvkah5vh4y0mEOzCHbbKPcutV4DiSKsbEnlgmuNkdu4jumYdaHYJqUT57n");

但正如预期的那样,它没有帮助。

我试图通过get请求获取令牌,但响应不包含任何令牌。

有什么想法吗?

我正在使用最新版本的Xamarin Forms(2.3.3.175)。

0 个答案:

没有答案