C# 在MVC中使用AJAX写入HTTP头
基本上,我在这里的一些人的帮助下编写了一个控制器,将一些基本授权提交到服务器的HTTP请求中。这基本上是将用户名和密码编码到API上的特定URLC# 在MVC中使用AJAX写入HTTP头,c#,jquery,asp.net,ajax,asp.net-mvc,C#,Jquery,Asp.net,Ajax,Asp.net Mvc,基本上,我在这里的一些人的帮助下编写了一个控制器,将一些基本授权提交到服务器的HTTP请求中。这基本上是将用户名和密码编码到API上的特定URL $(document).ready(function () { $.ajax({ url: "vebra/", type: "POST", }) }); 上面是我的ajax请求,它在调用vebra控制器运行的报头中启动。 我还是C&ASP新手,不确定我在jquery上的输入是否正确 下面是我的控制器:
$(document).ready(function () {
$.ajax({
url: "vebra/",
type: "POST",
})
});
上面是我的ajax请求,它在调用vebra控制器运行的报头中启动。
我还是C&ASP新手,不确定我在jquery上的输入是否正确
下面是我的控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Caching;
using System.Text;
using System.Web.UI;
using System.Web.Mvc;
namespace com.tortoise.Controllers
{
public class VebraController : Controller
{
//
// GET: /vebra/
string username = "foo";
string password = "foo";
string url = "http://mywebservice.com";
public VebraController ()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string usernamePassword = (username + ":" + password);
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(url), "Basic", new NetworkCredential (username,password));
request.Credentials = cache;
request.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the token from the response:
string token = response.GetResponseHeader("Token");
}
}
}
其思想是,在request.Headers.Add行上,它应该解析上面创建的凭据,并将其放在发送给服务器的http头请求中,以便传递基本授权并返回一个令牌值,该令牌值授权xml访问1小时
然而,当我运行这个程序时,根据Fiddler告诉我的,它没有显示被放入http头请求的迹象
这可能是我在这里遗漏的内容,但任何指针都会非常有用。假设您引用的是对服务的基本Auth头请求,我无法复制。复制了你的代码,除了CredentialCache的东西,不确定它的用途,还有基本的AUTH头,Authorization:BASIC Zm9vOmZvbw==正确发送,我用它代替了Fiddler。嗯…@EdSF这个auth的东西似乎已经生成了,而且一切都正常,我同意。然而,我的问题是Authorization:Basic没有被放入到服务器的HTTP头中。我不明白为什么…我是说,在我的测试中,复制你的代码时,不管有没有凭证缓存部分,它都是被编写和发送的。请看@EdSF,我猜requestb.in会执行一个直接的HTTP头请求。我的问题是,这段代码在控制器中,我正试图在对服务器的HTTP头请求中执行这段代码/控制器。我想这就是我的问题所在。不完全是,我正在控制器中运行您的代码,并发布到Requestbin。Requestbin所做的只是向您显示您发送给它进行调试的内容,等等。