dtqf81594 2014-10-06 21:25
浏览 91

Razor(cshtml)相当于使用cURL(php)来调用rest api

I've successfully made a call to the rest api using curl like this:

 $curl = curl_init();

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $_POST["logInEmail"] . ":" . $_POST["logInPassword"]);

curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, "http://<theURL>/api/session");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($curl);

curl_close($curl);

echo $result; //for testing, otherwise it would be inside a function and use return...

However, my work project is not in php, so I can't use this. I tried with AJAX but I get "Cross-Origin Request Blocked", so I have to look into doing this in Razor (cshtml).

I'd like to know if it is even possible to write this in cshtml.

UPDATE: I got it to work eventually so I will post the code in case someone needs it in the future.

string _auth = string.Format("{0}:{1}", "username","password");
string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));

var url = "http://api url";

var client = new WebClient();

client.Headers.Add("contentType", "application/json");
client.Headers.Add("Authorization", "BASIC " + _enc);

var content = client.UploadString(url, "");
var search = Json.Decode(content);

Then just I use the search variable to use the data from the response (in this case it returns user's details and auth token and I set up a local session).

Also if someone can explain why this should not be done in a razor script, that will be great (as per Morten OC's comment).

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器