我创建了一个 C# WebMethod
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static HttpResponseMessage GetPageHtml(string file, int page)
{}
当我添加 header Content-Type : 'application/Json' 时,我可以调用它并且使用 Ajax、angular、Postman 可以正常工作。这是工作正常的示例 HTTP 请求。
$http({
url: 'default.aspx/GetPageHtml?file=' + JSON.stringify(selectedFile) + '&page=' + itemNumber,
method: "GET",
headers: { 'Content-Type': 'application/json' },
data:''
}).then(function successCallback(response) {
return response.d;
}, function errorCallback(response) {
});
但是当我为 iframe ng-src 调用相同的方法时,它不起作用。
<iframe ng-src="default.aspx/GetPageHtml?file=candy.pdf&page=1" style="height: 150px;"></iframe>
我通过 Google Chrome 的开发人员工具检查了这个 Http 调用,发现那里的 Content-Type 是“text/html”,这就是它没有访问我的 WebMethod 的原因。请看这个截图。 Iframe ng-src
我在 Google 和 Stackoverflow 上进行了很多调查,但找不到我需要提供 Content-Type : 'application/json' 来调用我的 WebMethod 的原因
最佳答案
我进一步调查了我的问题并尝试找到其他解决方法,我想出了一个解决方案。我创建了一个名为 GetDocumentHtml.aspx
的新 WebForm,并在其 Page_Load
方法中执行了我之前在 GetPageHtml
WebMethod 中执行的操作
。
现在在 iframe
ng-src
我提供这个 URL
/GetDocumentHtml.aspx?file=calibre.docx&page=1
代替
default.aspx/GetPageHtml?file=candy.pdf&page=1
在 Page_Load 方法中,我使用以下代码获取 URL 参数
var file = GetValueFromQueryString("file");
var page =Convert.ToInt32(GetValueFromQueryString("page"));
GetValueFromQueryString 方法
private String GetValueFromQueryString(String value)
{
try
{
return Request.QueryString[value].ToString();
}
catch (System.Exception exp)
{
return String.Empty;
}
}
我希望这些信息对某些人有所帮助。谢谢。
关于javascript - 当未提供内容类型 '' 应用程序/Json 时,C# [WebMethod] 未命中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43721222/