簡體   English   中英

當沒有提供Content-Type''application / Json“時,C#[WebMethod]沒有命中

[英]C# [WebMethod] is not hitting when Content-Type ''application/Json" is not provided

我創建了一個C#WebMethod

  [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public static HttpResponseMessage GetPageHtml(string file, int page)
    {}

我可以調用它,當我添加標題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>

我通過谷歌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;
        }
    }

我希望這些信息對某人有所幫助。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM