Chr*_*ris 7 rest wcf uwp asp.net-core
我试图了解如何在UWP/UAP应用程序中使用ASP.NET Core WebAPI.我以为我可以使用类似于使用WCF服务的WebAPI,但我还没有找到任何相关内容.
此外,我尝试安装Microsoft.AspNet.WebApi.Core但没有成功,因为它与UAP(版本= V10.0)不兼容.
我现在有点迷失了.也许有人可以告诉我如何在UWP应用程序中使用WebApi.
这与使用任何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; }
}
Run Code Online (Sandbox Code Playgroud)
假设它托管在`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!' }"
}
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以将此反序列化为强类型对象使用Newtonsoft.Json
.我有一个我的UWP应用程序在这里做这件事的例子.
我将添加更多信息:
在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
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您决定支持其他平台(如Xamarin Android或iOS),通过此类实施,您可以在将来共享代码.我希望这能帮到您.
归档时间: |
|
查看次数: |
18110 次 |
最近记录: |