2016-06-14 74 views
0

無法從angularjs控制器調用webservice函數。 它正在訪問該文件,但功能無法訪問。 錯誤:無法調用webservice函數angularjs

  1. 服務器迴應500(內部服務器錯誤)的狀態
  2. System.InvalidOperationException:Web服務方法名稱無效。在 System.Web.Services.Protocols.HttpServerProtocol.Initialize()在 System.Web.Services.Protocols.ServerProtocolFactory.Create(類型類型, HttpContext的上下文中,請求的HttpRequest,HttpResponse對象響應, 布爾& abortProcessing)
namespace AngularJSTesting.App{ 

    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class WebService2 : System.Web.Services.WebService 
    { 

     string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TextItConnectionString"].ToString(); 



     [WebMethod] 
     [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
     public string FetchData() 
     { 
      DataTable dt = new DataTable(); 
      using (SqlConnection con = new SqlConnection(connectionString)) 
      { 
       using (SqlCommand cmd = new SqlCommand("select UserName, Name, Email, PhoneNumber from new_users where UserId < 11 order by UserId asc ", con)) 
       { 
        con.Open(); 
        SqlDataAdapter da = new SqlDataAdapter(cmd); 
        da.Fill(dt); 
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); 
        Dictionary<string, object> row; 
        foreach (DataRow dr in dt.Rows) 
        { 
         row = new Dictionary<string, object>(); 
         foreach (DataColumn col in dt.Columns) 
         { 
          row.Add(col.ColumnName, dr[col]); 
         } 
         rows.Add(row); 
        } 
        return serializer.Serialize(rows); 
       } 
      } 
     } 

     [WebMethod] 
     // [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
     public static string read() 
     { 
      return "test"; 
     } 
    } 
    } 

JS文件

'use strict'; 

app.controller('aboutController', function ($scope, $http) { 
$scope.message = "Now viewing About!"; 

var url = 'WebService2.asmx/read'; 
$http.get(url) 
      .success(function (data) { 
       alert("success"); 
       $scope.users = data; 

      }) 
      .error(function (data) { 
       alert("error"); 
       alert(data); 
      }) 
}); 

回答

0

您需要將Script Method Get Attribute[ScriptMethod(UseHttpGet = true)]添加到網絡方法。 也從函數簽名中刪除static

[WebMethod] 
[ScriptMethod(UseHttpGet = true)] 
public string read() 
{ 
    return "test"; 
} 
+0

已經做到了。什麼都沒發生 –

+0

@MuhammadTauseen你有沒有嘗試刪除'static'關鍵字 –

+0

是的。 找到解決辦法;如果不部署它就無法訪問webservice的功能 –