在jQuery中使用MapPageRoute调用WebMethod

时间:2013-12-13 11:29:15

标签: c# asp.net jquery web

我想在ASP.Net中使用jQuery Ajax,我在JavaScript中使用下面的代码

$(function () {
        $('#click').click(function () {
            $.ajax({
                type: "POST",
                url: "mine/HelloAgain",
                data: JSON.stringify({ID : 236 , Name : "Milad"}),
                contentType: "application/json",
                dataType: "json",
                success: function (msg) {
                    $("#Result").text(msg.d);
                }
            });
        });

    });

正如你在url中看到我使用[mine / HelloAgain]并在此代码中创建Global for routing

routes.MapPageRoute("Mine",
        "mine/{*locale}",
        "~/tst/Test.aspx/HelloAgain",
        true
        );

但返回404 Not Found错误此WebMethod我想调用

[WebMethod]
public static string HelloAgain(int ID, string Name)
{
    return ID.ToString() + " Hello " + Name + DateTime.Now.ToString(); 
}

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您无法使用方法

routes.MapPageRoute("Mine",
"mine/{*locale}",
"~/tst/Test.aspx/HelloAgain",
true
);

仅用于将页面映射到某个路径。 我发现只有一个解决方案来映射非Page端点:创建自定义路由处理程序并调用它。 例如,Global.asax:

routes.Add("Authorization", new Route("Authorization", new GenericRouteHandler<AuthorizationHandler>()));

通用路由处理程序:

public class GenericRouteHandler<T> : IRouteHandler where T : IHttpHandler, new()
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
    return new T();
}
}

授权处理程序:

public class AuthorizationHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
    var requestData = JsonHelper.DeserializeJson<Dictionary<string, string>>(context.Request.InputStream);
    context.Response.ContentType = "text/json";
    switch (requestData["methodName"])
    {
        case "Authorize":
            string password = requestData["password"];
            string userName = requestData["name"];
            context.Response.Write(JsonHelper.SerializeJson(Authorize(userName, password)));
            break;
    }
}

public bool IsReusable
{
    get { return true; }
}

public object Authorize(string name, string password)
{
    User user = User.Get(name);
    if (user == null)
        return new { result = "false", responseText = "Frong user name or password!" };
    else
            return new { result = true};
}

此外,您可以使用Reflection来调用方法,例如:

Type thisHandlerType = GetType();
var methodToCall = thisPage.GetMethod(requestData["methodName"]);
if (methodToCall != null)
{
       var response = methodToCall.Invoke(this, new object[]{requestData});
       context.Response.Write(JsonHelper.SerializeJson(response));
}

public object Authorize(Dictionary<string, string> inputData)
{
    User user = User.Get(inputData["name"]);
    if (user == null)
        return new { result = "false", responseText = "Frong user name or password!" };
    else
            return new { result = true};
}

More about custom mapping to custom RouteHandlers

相关问题