我试图了解如何在UWP / UAP应用程序中使用ASP.NET Core WebAPI。 我以为我可以使用类似于使用WCF服务的WebAPI,但我还没有找到任何相关内容。
此外,我尝试安装Microsoft.AspNet.WebApi.Core但没有成功,因为它与UAP(版本= V10.0)不兼容。
我现在有点迷失了。也许有人可以给我一个如何在UWP应用程序中使用WebApi的提示。
答案 0 :(得分:7)
这与使用任何API调用相同。只需使用HttpClient
类来调用端点并处理响应,预期行为没有区别。
假设您有一个 ASP.NET Core Web API 端点定义如下:
public class StackoverflowController : Controller
{
// I wanted to exemplify async capabilities.
// You'd use async/await for getting database values, etc.
[
HttpGet,
AllowAnonymous,
Route("api/greeting")
]
public Task<GreetingResult> Greeting() =>
Task.FromResult(new GreetingResult { Message = "Hello world!" });
}
public class GreetingResult
{
public string Message { get; set; }
}
假设它托管在`localhost:5000'上,您可以执行以下操作:
public class Consumer
{
public async Task<string> GetGreetingAsync()
{
using (var client = new HttpClient())
{
var response =
await client.GetStringAsync("http://localhost:5000/api/greeting");
// The response object is a string that looks like this:
// "{ message: 'Hello world!' }"
}
}
}
此外,您可以使用Newtonsoft.Json
将其反序列化为强类型对象。我有一个关于我的UWP应用程序的例子here。
答案 1 :(得分:5)
我将为此添加更多信息:
在UWP中使用Web Api的最佳方法是使用前面提到的HttpClient。
以下是我认为可能有用的一些例子。
最佳做法是创建MobileServiceClient类,您可以在其中收集可在Web Api级别执行的所有操作:
public class MobileServiceClient
{
//access token if you use authentication:
private string _accessToken;
//address of your Web Api:
private string _serviceAddress;
//Constructor:
public MobileServiceClient(string accessToken, string serviceAddress)
{
_accessToken = accessToken;
_serviceAddress = serviceAddress;
}
//Now you can implement methods that you will invoke to perform selected operation related with Web Api:
#region Methods
//You can perform "Get" to retrieve object from the Web Api and then deserialize it (using Json .NET):
public async Task<SampleClass> GetSampleClass()
{
SampleClass sampleClass= null;
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accessToken);
var data = await client.GetAsync(string.Concat(_serviceAddress, "routeName"));
var jsonResponse = await data.Content.ReadAsStringAsync();
if (jsonResponse != null)
sampleClass= JsonConvert.DeserializeObject<SampleClass>(jsonResponse);
return sampleClass;
}
}
catch (WebException exception)
{
throw new WebException("An error has occurred while calling GetSampleClass method: " + exception.Message);
}
}
//You can perform "Get" to retrieve list of objects and then deserialize it:
public async Task<List<SampleClass>> GetSampleClassObjects()
{
List<SampleClass> SampleClassObjectsList = null;
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accessToken);
var data = await client.GetAsync(string.Concat(_serviceAddress, "routeName"));
var jsonResponse = await data.Content.ReadAsStringAsync();
if (jsonResponse != null)
SampleClassObjectsList = JsonConvert.DeserializeObject<List<SampleClass>>(jsonResponse);
return SampleClassObjectsList;
}
}
catch (WebException exception)
{
throw new WebException("An error has occurred while calling GetSampleClassObjects method: " + exception.Message);
}
}
//You can also "Post" some object:
public async Task<bool> PostSomeObject(SampleClass sampleClassObject)
{
try
{
using (HttpClient client = new HttpClient())
{
var sampleClassObjectJson = JsonConvert.SerializeObject(sampleClassObject);
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accessToken);
var content = new StringContent(sampleClassObjectJson, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(string.Concat(_serviceAddress + "routeName"), content);
if (response.StatusCode == HttpStatusCode.OK)
return true;
else
throw new WebException("An error has occurred while calling PostSomeObject method: " + response.Content);
}
}
catch (WebException exception)
{
throw new WebException("An error has occurred while calling PostFeedback method: " + exception.Message);
}
}
#endregion
}
请注意,如果您决定支持其他平台(如Xamarin Android或iOS),通过此类实施,您可以在以后共享代码。 我希望这会对你有所帮助。
答案 2 :(得分:3)
如果您使用Swagger(例如,Swashbuckle Swagger 6.0用于ASP.NET Core)来描述RESTful API并为其生成文档,则可以使用swagger定义文件(swagger.json)生成Rest Client。其中一个工具是AutoRest,由Azure团队创建。它还需要Microsoft.Rest.ClientRuntime已经支持DotNet。
我不确定它是否与ASP.NET Core RTM一起运行,但是已经解决/已关闭的问题表明它支持以前的版本并将beta合并到其中。
NuGet包链接