【发布时间】: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