【问题标题】:Call Secure ASP.Net API from Windows 8 Phone App with WebClient使用 WebClient 从 Windows 8 Phone App 调用 Secure ASP.Net API
【发布时间】:2016-01-11 21:47:49
【问题描述】:

我根据这个教程创建了自己的 Windows Phone 应用程序:http://www.asp.net/web-api/overview/mobile-clients/calling-web-api-from-a-windows-phone-8-application

到目前为止,一切正常。

现在我使用 [身份验证] 保护了我的控制器。 当我从浏览器调用 API 时,我会被重定向到带有 Auth 表单的登录页面。

当我尝试从我的手机应用程序中获取记录时也是如此。谁能帮我编写 webClient 代码以使用 Windows 8 Phone 应用程序从 webapi 获取我的所有数据?

Asp.net API Controller:
 public class AlertsController : ApiController
    {
        private AlertRepository repository = null;

        public AlertsController()
        {
            this.repository = new AlertRepository();
        }

        [HttpGet]
        [Authorize]
        public HttpResponseMessage Get()
        {
            IEnumerable<AlertDetails> alerts = this.repository.ReadAllAlerts();
            if (alerts != null)
            {
                return Request.CreateResponse<IEnumerable<AlertDetails>>(HttpStatusCode.OK, alerts);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
        }
enter code here



The WebClient in MainViewModel from the PhoneApp:

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using AlertCatalog.Resources;
using System.Net;
using AlertCatalog.Models;
using Newtonsoft.Json;


namespace AlertCatalog.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        const string apiUrl = @"http://localhost:25518/api/Alerts";
            public MainViewModel()
        {
            this.Items = new ObservableCollection<ItemViewModel>();
        }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<ItemViewModel> Items { get; private set; }

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        /// 
        //Create an instance of your new CookieAware Web Client



public void LoadData()
        {
            if (this.IsDataLoaded == false)
            {
                this.Items.Clear();
                this.Items.Add(new ItemViewModel() { ID = "0", LineOne = "Please Wait...", LineTwo = "Please wait while the catalog is downloaded from the server.", LineThree = null });
                WebClient webClient = new WebClient();
                webClient.Credentials = new NetworkCredential("testusername", "testpassword");
                webClient.Headers["Accept"] = "application/json";
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadCatalogCompleted);
                webClient.DownloadStringAsync(new Uri(apiUrl));
            }
        }

        private void webClient_DownloadCatalogCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                this.Items.Clear();
                if (e.Result != null)
                {
                    var alerts = JsonConvert.DeserializeObject<AlertDetails[]>(e.Result);
                    int id = 0;
                    foreach (AlertDetails alert in alerts)
                    {
                        this.Items.Add(new ItemViewModel()
                        {
                            ID = (id++).ToString(),
                            LineOne = alert.Severity,
                            LineTwo = alert.Name,
                            LineThree = alert.Description.Replace("\n", " ")
                        });
                    }
                    this.IsDataLoaded = true;
                }
            }
            catch (Exception ex)
            {
                this.Items.Add(new ItemViewModel()
                {
                    ID = "0",
                    LineOne = "An Error Occurred",
                    LineTwo = String.Format("The following exception occured: {0}", ex.Message),
                    LineThree = String.Format("Additional inner exception information: {0}", ex.InnerException.Message)
                });
            }
        }

错误消息: Error from PhoneApp

【问题讨论】:

    标签: asp.net security asp.net-web-api webclient


    【解决方案1】:

    简单地添加webClient.Credentials = new NetworkCredential("testusername", "testpassword");并不意味着你的api会识别用户为授权用户。

    您可以从AuthorizeAttribute派生来指定您自己的授权规则。

    例如

    public class MyAuthAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //Implement your own checks here
            //httpContext.Request.Headers["yourHeaderToCheck"]
            return true;
        }
    }
    

    然后将[Authorize]替换为[MyAuth]

    【讨论】:

      猜你喜欢
      • 2014-02-28
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多