【问题标题】:Calling secure Web Api from Xamarin.Ios not working从 Xamarin.Ios 调用安全 Web Api 不起作用
【发布时间】:2016-04-12 21:35:30
【问题描述】:

我正在尝试访问我的服务器上需要从 Xamarin.Ios 应用程序进行身份验证 (Google/Facebook) 的安全 Web api。

从 azure 门户下载并运行示例 ToDo 应用程序,并添加本教程中的身份验证 https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-xamarin-ios-get-started-users/ 就像使用 google 和 facebook 的魅力一样。

但是当我创建一个快速的 ASP.NET 应用程序并添加一个 Web Api 2 控制器,并尝试从 Xamarin.Ios 调用它时,它甚至无法访问它。

例如,有这个控制器:

public class GetAdviceController : ApiController
{
    [HttpGet]
    [Authorize]
    [ResponseType(typeof(string))]
    public IHttpActionResult GetAdvice()
    {
        return Ok("RandomAdvice/Passed");
    }
}

Xamarin.Ios 中的这段代码

    public MobileServiceClient Client = new MobileServiceClient(Constants.ApplicationURL);
    HttpClient restClient= new HttpClient();

        try
        {
            MobileServiceUser User = await App.Client.LoginAsync(this, MobileServiceAuthenticationProvider.Google);
            //User contains the Token and SID

            Console.Error.WriteLine(@"Logged IN");

            HttpResponseMessage response = new HttpResponseMessage();
            try
            {
                response = await client.GetAsync("https://mysite.azurewebsites.net/api/getadvice");

     //The response is 200 but it does not reach my controller and redirests me to the login screen of the asp.net website. http://imgur.com/Fp9FhdR


            }
            catch (Exception ex)
            {
                 Console.WriteLine( ex.Message);
            }

response.content 是 http://imgur.com/Fp9FhdR,只是 JSON 格式。

我确定我遗漏了一些东西,但我就是找不到它是什么。 谢谢。

【问题讨论】:

  • 您是否在任何地方的任何标题中设置了令牌?我没有看到任何表明这一点的东西。

标签: azure asp.net-web-api xamarin xamarin.ios authorization


【解决方案1】:

应该检查双方:服务器和客户端:

在服务器上,确保您有 [MobileAppController] 用于 Web API 控制器

[MobileAppController]
public class GetAdviceController : ApiController
{
}

客户端Xamarin,如果你想使用经典的HttpClient向Web API(Azure服务器)发出请求,需要添加几个Headers:

HttpClient restClient= new HttpClient();
restClient.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));
restClient.DefaultRequestHeaders.Add ("ZUMO-API-VERSION", "2.0.0");
restClient.DefaultRequestHeaders.Add ("X-ZUMO-AUTH", token);
restClient.GetAsync(....);

使用您已通过 Google 验证的用户对象中的 token

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多