Asp.net 如何通过jQueryAjax调用将参数传递给控制器中的方法
我正在使用asp.NETWebAPI。我试图使用jqueryajax调用调用controller(Security)。我的控制器中有一个方法,有3个参数,比如Asp.net 如何通过jQueryAjax调用将参数传递给控制器中的方法,asp.net,jquery,asp.net-web-api,Asp.net,Jquery,Asp.net Web Api,我正在使用asp.NETWebAPI。我试图使用jqueryajax调用调用controller(Security)。我的控制器中有一个方法,有3个参数,比如 public WebRequest GetRequest(string method,string type,string endpoint) { RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); var request
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个参数(方法、类型、端点)中显示空值。指引我。你需要这个:
data: { 'method': method, 'type': type, 'endpoint': endpoint },
这将传递请求中的值,尽管在您的示例中,我不确定如果端点的值是控制器/操作的URL,为什么需要将端点作为参数传递给方法?您需要
1) 更改GET以将数据发布为JSON。GET不能包含内容。
2) 将数据作为查询字符串参数传递
如果我自己做,我会选择案例2:
http://localhost:49847/api/Security?method=someMethod&type=someType&endpoint=someendpoint
由于这是与安全相关的,它必须是HTTPS
但我不会自己做,而是使用安全专家开发的:“Thinktecture.IdentityModel.40”
@Aliostad您可以通过GET或POST传递数据。文档声明数据将添加到查询字符串中以获取。谢谢你能更新你的帖子吗,这样我就可以把-1改成+1了?任何更新都可以。所以不允许我在几分钟后更改mu upvote DOWNSPOTE。@Aliostad我已经尝试过了!您不需要转换为POST或自己手动编写查询字符串。查看jQuery文档: