我对Web服务世界很陌生,所以请耐心等待.我正在使用.asmx文件在Visual Studio 2010中创建一个非常简单的Web服务.
这是我正在使用的代码:
namespace MyWebService
{
[WebService(Namespace = "http://www.somedomain.com/webservices")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string simpleMethod(String str)
{
return "Hello " + str;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用它并为str参数输入值"John Smith"时,它返回:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.somedomain.com/webservices">Hello John Smith</string>
Run Code Online (Sandbox Code Playgroud)
我的问题是,为Web服务方法返回超过1个值的最佳做法是什么?如果值都是相同的数据类型,我应该使用数组吗?如果值包含不同的数据类型,我需要创建自定义类吗?
如果我使用已安装的Nuget软件包Microsoft.AspNet.FriendlyUrls v 1.0.2和Microsoft.AspNet.Identity v.1.0.0.从jQuery.Ajax调用webmethod,那么我得到数据对象,但是没有data.d但是有属性Message '身份验证失败'.
我的Webmethod.aspx是:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>WebMethod</title>
<script src="Scripts/jquery-2.0.3.js"></script>
</head>
<body>
<form id="form1" runat="server">
<h3>Test Webmethod</h3>
<div id="greeitng"></div>
<div id="innerError" style="border:1px dotted red;display:none;" title="errorMessage"></div>
<script type="text/javascript">
function asyncServerCall(username) {
jQuery.ajax({
url: 'WebMethod.aspx/HelloWorld',
type: "POST",
data: "{'username':'" + username + "'}",
//async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d == undefined)
document.getElementById("greeitng").innerHTML = data.Message;
else
document.getElementById("greeitng").innerHTML = data.d;
},
error: function (err) {
if (err.responseText) { …Run Code Online (Sandbox Code Playgroud) 我在标记为a的页面上有一个方法,[WebMethod]它使用一些会话状态作为其操作的一部分.在我编写这段代码之后,EnableSessionState当你在a中使用会话状态时,我突然想要使用闪存[WebMethod](例如,请参阅此处:http://msdn.microsoft.com/en-us/library/byxd99hx.aspx) .但似乎工作正常.为什么?
示例代码背后:
protected void Page_Load(object sender, EventArgs args) {
this.Session["variable"] = "hey there";
}
[System.Web.Services.WebMethod]
public static string GetSessionVariable() {
return (string)HttpContext.Current.Session["variable"];
}
Run Code Online (Sandbox Code Playgroud)
样本体html:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getSession() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetSessionVariable',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
document.getElementById("showSessionVariable").innerHTML = msg.d;
}
});
return false;
}
</script>
<form id="form1" runat="server">
<div id="showSessionVariable"></div>
<button onclick='return getSession()'>Get Session Variable</button>
</form>
Run Code Online (Sandbox Code Playgroud) 我试图从jQuery传递一些简单的JSON到ASP.NET 4.5 Webmethod.它并没有像我想要的那样工作.如果我接受输入作为单独的参数,它可以工作:
[WebMethod]
public static Address GetJSonAddress(string name, string street)
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试将它作为一个对象,它不起作用,传入的内容只是null:
[WebMethod]
public static Address GetJSonAddress(Address newAddress)
Run Code Online (Sandbox Code Playgroud)
我尝试过使用DataContractJsonSerializer的Webmethods,Pagemethods,WCF ......没什么.Address类使用Datamember/DataContract进行适当修饰.属性匹配包括案例.
jQuery,我在其中尝试了所有传递数据的方式,包括将它包装在Address对象中......如果我以任何其他方式执行它而不是我的Webmethod没有被调用,我得到错误500:
Save2 = function () {
var address = { prefix: GLOBALS.curr_prefix };
$('input[id^=' + GLOBALS.curr_prefix + '],select[id^=' + GLOBALS.curr_prefix + ']').each(function () {
address[this.id.substr(4)] = $.trim($(this).val());
})
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/WebServices/Insert",
data: JSON.stringify(address),
dataType: "json",
success: function (data, textStatus) {
console.log(data, textStatus);
},
failure: function (errMsg) {
MsgDialog(errMsg);
}
});
}
Run Code Online (Sandbox Code Playgroud)
最终我将不得不使用121个输入字符串执行此操作,并且实际上不希望有一个包含121个参数的方法.任何帮助表示赞赏.
我在default.aspx.cs文件中声明了一个WebMethod.
[WebMethod]
public static void ResetDate()
{
LoadCallHistory(TheNewDate.Date);
}
Run Code Online (Sandbox Code Playgroud)
为什么必须将WebMethod方法声明为静态?
我有一个default.aspx.cs,其中包含我要调用的webmethod,我的js文件包含了我的jquery ajax.我不能称之为webmethod.
这是我的default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string[] MyArray = new string[1];
MyArray[0] = "My Value";
Grid1D.DataSource = MyArray;
Grid1D.DataBind();
}
[WebMethod]
public Details[] getDetails(string columnname, string inputVal)
{
List<Details> list = new List<Details>();
DbAccess dbacc = new DbAccess();
DataTable dt = dbacc.getReportDetails(columnname, inputVal);
foreach (DataRow row in dt.Rows)
{
Details _Details = new Details();
_Details.memid = row["memid"].ToString();
_Details.usrname = row["usrname"].ToString();
_Details.fullname = row["fullname"].ToString();
_Details.fname = row["fname"].ToString();
_Details.mname = row["mname"].ToString();
_Details.lname = row["lname"].ToString();
_Details.bdate = row["bdate"].ToString();
_Details.address …Run Code Online (Sandbox Code Playgroud) 这是Visual Studio中的一个C#Web服务项目,已经存在了很多年.今天它开始在Visual Studio中启动时抛出异常,但只有在附加调试器时才会抛出异常.
例外是:
System.StackOverflowException was unhandled
Message: An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
Run Code Online (Sandbox Code Playgroud)
这是Visual Studio 2013 Update 3.
堆栈跟踪的相关部分:
System.Runtime.Serialization.dll!System.Runtime.Serialization.Json.JsonDataContract.WriteJsonValue(System.Runtime.Serialization.XmlWriterDelegator jsonWriter, object obj, System.Runtime.Serialization.Json.XmlObjectSerializerWriteContextComplexJson context, System.RuntimeTypeHandle declaredTypeHandle) Unknown
System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(System.Runtime.Serialization.XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, System.RuntimeTypeHandle declaredTypeHandle) Unknown
System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(System.Runtime.Serialization.XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, System.RuntimeTypeHandle declaredTypeHandle) Unknown
[Lightweight Function]
System.Runtime.Serialization.dll!System.Runtime.Serialization.Json.JsonDataContract.WriteJsonValue(System.Runtime.Serialization.XmlWriterDelegator jsonWriter, object obj, System.Runtime.Serialization.Json.XmlObjectSerializerWriteContextComplexJson context, System.RuntimeTypeHandle declaredTypeHandle) Unknown
System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(System.Runtime.Serialization.DataContract dataContract, System.Runtime.Serialization.XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, System.RuntimeTypeHandle declaredTypeHandle, System.Type …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个新的网页,我需要显示近10个不同的网格视图和图表.
Gridview在pageload事件中绑定,并且通过调用WebMethod使用jquery-ajax方法(使用amcharts以及highcharts)显示图表.
最初我执行页面的方式是在执行gridview(用于显示网格视图数据)和webmethods(用于绘制图表)的同一组存储过程之后.对于此页面,执行两次相同的sps(一个用于网格,另一个用于图表) ).为获取数据需要执行10个sps.
因此,为了提高页面性能,我创建了这样的静态数据表
static DataTable Report1;
Run Code Online (Sandbox Code Playgroud)
并且像这样捆绑了gridview.
private void gvbindReport1()
{
try
{
Report1 = new DataTable();//refreshed datatable
DataSet ReportDS1 = objmvbl.GetReportGraph(ClientID, date_From, date_To);
if (ReportDS1.Tables.Count > 0)
{
Report1 = ReportDS1.Tables[0];//bindinding data to static datatable
}
GdReport.DataSource = Report1;
GdReport.DataBind();
}
catch (Exception ex)
{
Log.Errlog("Error Occured in gvbindReport1 : " + ex.Message.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
在webmethod内部,我使用了相同的数据表来绘制图表
[System.Web.Services.WebMethod]
public static string GetDataReport1()
{
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; …Run Code Online (Sandbox Code Playgroud) 在我的ASP.NET网站中,我使用Jquery调用Web方法,如下所示:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{'param1': '" + param1 + "','param2': '" + param2+ "' }",
dataType: 'json',
url: "Default.aspx/TestMethod",
error: function (jqXHR, textStatus, errorThrown) {
alert("error: " + textStatus);
},
success: function (msg) {
document.getElementById("content").innerHTML = msg.d;
}
});
Run Code Online (Sandbox Code Playgroud)
Web方法定义是:
[System.Web.Services.WebMethod]
public static String TestMethod(String param1, String param2)
{
String to_return = /* result of operations on param1 and param2 */;
return to_return;
}
Run Code Online (Sandbox Code Playgroud)
我的结果是一个包含HTML代码的String.
如果to_return字符串很小,它是完美的.
但它给我的错误是:
500内部服务器错误6.22s
我尝试使用FireBug在Response中探索它,它向我展示:
{"Message":"处理请求时出错.","StackTrace":"","ExceptionType":""}
在Visual Studio中使用断点,我已将to_return字符串复制到文本文件中.文件大小变为:127 …
我正在尝试了解web api和一些有关Web方法的新闻.我听说我们应该停止使用几种来源的网络方法.另外,如果不再使用Web方法,Web API是继承者吗?