将AJAX REST调用转换为c# . net
本文关键字:net 转换 调用 AJAX REST | 更新日期: 2023-09-27 18:14:48
我有一个AJAX调用,它在本地服务器上完美地工作。我正试图通过c#(从另一个应用程序/域)进行相同的调用,但我非常困惑。
这是我的webmethod:
[WebMethod(true)]
public static object ParentLogin(string email, string password)
{
List<object> ChildrenList = new List<object>();
Usuario loggedUser = GetByEmailAndPass(email, password);
if (loggedUser != null)
{
var children = Factory.Current.GetInstance<IChildrenBIZ>().GetAll().ToList();
foreach (var item in children )
{
ChildrenList.Add(new { userid = item.Id, name = item.Nome });
}
return new { success = true, email = loggedUser.Login, users = ChildrenList};
}
return new { success = false };
}
这是我的ajax调用:
var url = "http://localhost/" + "LoginTest/Login.aspx/ParentLogin";
var dataParams = "{ email: " + "'myemail@hotmail.com'" + ", password: " + "'123123'" + " }";
ExecuteAjaxCall(url, dataParams, true, function (msg) {
if (msg.d) {
var success = msg.d.success;
var children = msg.d.users;
if (children.length > 0) {
$.each(children, function (i, item) {
if (item) {
var childID = item.userid;
}
});
}
}
}, StandardError);
});
现在我想通过后面的代码调用相同的webmethod。我试着用Restsharper,但我做不到。任何人,好吗?
编辑:这是ExecuteAjaxCall方法:
function ExecuteAjaxCall(url, dataParam, isAssync, callBackSucess, callBackError) {
$.ajax({
type: "POST",
url: url,
data: dataParam,
contentType: "application/json; charset=utf-8",
dataType: "json",
assync: isAssync,
success: function (msg) {
callBackSucess(msg);
},
error: function (msg) {
callBackError(ERROR_MSG);
}
});
}
重要:
我想这样做的主要原因是因为我想从另一个域使用ParentLogin方法。也许来自iOS或Android应用程序!这是正确的方法吗?
谢谢!
这个web方法(实际上是一个"Page method ")是web应用程序中的一个公共静态方法。你应该可以直接调用它:
namespace.Login.ParentLogin(email, password);
我会重构出一个服务类来容纳你的应用程序逻辑,这样你就可以在另一个项目中使用它而不是RestSharp。
[WebMethod(true)]
public static object ParentLogin(string email, string password)
{
return ServiceAdapter.ParentLogin(email, password);
}
public interface IService
{
object ParentLogin(string email, string password);
}
public sealed class Service : IService
{
public object ParentLogin(string email, string password)
{
List<object> ChildrenList = new List<object>();
Usuario loggedUser = GetByEmailAndPass(email, password);
if (loggedUser != null)
{
var children = Factory.Current.GetInstance<IChildrenBIZ>().GetAll().ToList();
foreach (var item in children )
{
ChildrenList.Add(new { userid = item.Id, name = item.Nome });
}
return new { success = true, email = loggedUser.Login, users = ChildrenList};
}
return new { success = false };
}
//TODO move GetByEmailAndPass
}
public sealed class ServiceAdapter
{
public static readonly IService Service = new Service();
}