我正在研究 asp.net web api。我正在尝试使用 jquery ajax 调用来调用控制器(安全)。我的控制器中有一个带有 3 个参数的方法,例如,
public WebRequest GetRequest(string method,string type,string endpoint)
{
RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
var request = WebRequest.Create(endpoint);
request.Method = method;
request.ContentType = type;
UnicodeEncoding enc = new UnicodeEncoding();
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
request.Headers.Add("Authorization-Token", RSAClass.StringConverter(RSAClass.RSAEncrypt(enc.GetBytes("User1"), rsa.ExportParameters(false), false)));
return request;
}
我正在做一个 jquery ajax 调用,比如,
CreateRequest("GET", "application/json;charset=utf-8", "http://localhost:49847/api/Security", function (request) { alert("Hello"); });
function CreateRequest(method, type, endpoint, callback) {
$.ajax({
url: "api/Security",
data: { method: method, type: type, endpoint: endpoint },
type: "GET",
contentType: "application/json;charset=utf-8",
statusCode: {
200: function (request) {
callback(request);
}
}
});
而且我还有 customfilterattribute 类来验证授权令牌,例如,
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
string token;
try
{
token = actionContext.Request.Headers.GetValues("Authorization-Token").First();
}
catch
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) { Content = new StringContent("missing authorization token") };
return;
}
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
UnicodeEncoding enc = new UnicodeEncoding();
AuthUsersRepository.GetAllUsers().First(x => x.Name ==enc.GetString(RSAClass.RSADecrypt(RSAClass.ByteConverter(token), RSA.ExportParameters(true), false)));
base.OnActionExecuting(actionContext);
}
catch
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { Content = new StringContent("Unauthorized User") };
return;
}
}
当我提出第一个请求时,它要求我提供授权令牌。并且还在 3 个参数(方法、类型、端点)中显示空值。引导我。