2013-12-13 37 views
1

我想在ASP.Net使用jQuery Ajax和我用下面的代码在JavaScript调用的WebMethod用的MapPageRoute jQuery中

$(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); 
       } 
      }); 
     }); 

    }); 

如您在网址看到我使用[矿山/ HelloAgain]我创建全局路由在此代码

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

您不能使用方法

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

是仅用于映射页面的一些路线。 我发现只有一种解决方案可以映射非页面端点:创建自定义路由处理程序并调用它。 例如,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}; 
} 

此外,您还可以使用反射来调用方法,例如:

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