我开发了一个角度应用程序,需要从远程服务器中使用json数据。由于CORS问题,应用程序无法直接从该服务器获取数据。我的解决方案是开发一个"代理" web api读取并将json返回给我的应用程序。目前,这就是我正在做的事情:
public async Task<IActionResult> MyJson()
{
const string jsonUrl = "url-of-remote-json";
using (var client = new HttpClient())
{
using (var result = await client.GetAsync(jsonUrl))
{
if (result.IsSuccessStatusCode)
{
return new ObjectResult(JsonConvert.DeserializeObject(await result.Content.ReadAsStringAsync()));
}
}
}
return new ObjectResult(new { });
}
但是,我认为这远非被认为是一种有效的方式,因为我必须将json读取为字符串,然后使用JsonConvert包将其转换为对象以提供web api方法。因此,表现并不是很好。
我想知道是否有更简单/有效/更简单的方法来完成这项任务?
答案 0 :(得分:2)
只需通过远程服务器的响应即可。看看编辑过的例子。
public async Task MyJson()//void if not async
{
string jsonUrl = "url-to-json";
HttpContext.Response.ContentType = "application/json";
using (var client = new System.Net.WebClient())
{
try
{
byte[] bytes = await client.DownloadDataTaskAsync(jsonUrl);
//write to response stream aka Response.Body
await HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
catch (Exception e)//404 or anything
{
HttpContext.Response.StatusCode = 400;//BadRequest
}
await HttpContext.Response.Body.FlushAsync();
HttpContext.Response.Body.Close();
}
}
按预期工作。
答案 1 :(得分:1)
这是@ Alex代码的修改版本,使用HttpClient代替WebClient:
public async Task MyJson()//void if not async
{
string jsonUrl = "url-to-json";
HttpContext.Response.ContentType = "application/json";
using (var client = new HttpClient())
{
try
{
byte[] bytes = await client.GetByteArrayAsync(jsonUrl);
//write to response stream aka Response.Body
await HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
catch (Exception e)//404 or anything
{
HttpContext.Response.StatusCode = 400;//BadRequest
}
await HttpContext.Response.Body.FlushAsync();
HttpContext.Response.Body.Close();
}
}
这是我的实际代码:
public async Task<IActionResult> MyJson()
{
const string jsonUrl = "url-to-json";
HttpContext.Response.ContentType = "application/json";
using (var client = new HttpClient())
{
try
{
byte[] bytes = await client.GetByteArrayAsync(jsonUrl);
//write to response stream aka Response.Body
await HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
await HttpContext.Response.Body.FlushAsync();
HttpContext.Response.Body.Close();
}
catch (Exception e)
{
return new BadRequestResult();
}
}
return new BadRequestResult();
}