簡體   English   中英

從 jQuery Ajax 發布到 WebAPI 2.1 controller 不起作用 - 沒有找到與 5URI 請求 POST5985DC6F62A6 匹配的 Z293C9EA246FF9785DC6F62A6 資源

[英]POSTing from jQuery Ajax to WebAPI 2.1 controller not working - No HTTP resource was found that matches the request URI

我在這里找不到答案(之前被問過,但這是特定於 MVC5 WebAPI2.1 和 jQuery),但在 Postman 中,我得到了

{ "Message": "沒有找到與請求 URI 'https://localhost:44371/api/reportdiscrepancy' 匹配的 HTTP 資源。", "MessageDetail": "在與要求。” }

錯誤消息 - 在那里(我有其他使用 GET 的控制器,但這個使用 POST 的控制器是唯一的區別,它們工作得很好)。 我的 controller (注意:這繼承自 ApiController,而不是控制器) - 當它是 ASMX 時,代碼運行良好:

  [Route("api/reportdiscrepancy")]
    [HttpPost]
    public async Task<IHttpActionResult> ReportDiscrepancy(string lid, string ProblemTypes, string ProblemTypeOther)
    {     
        string retval = string.Empty;
        lid = AppCore.Validation.StripToGUID(lid);
        ProblemTypes = AppCore.Validation.StripToDigitInCSVFromStr(ProblemTypes);
        ProblemTypeOther = AppCore.Validation.StripAllCharsForMetaTag(StripHtml(ProblemTypeOther));
        var session = HttpContext.Current.Session;

        if (lid.Length == 36 && ProblemTypes.Length > 0 | ProblemTypeOther.Length > 0)
        {
            if (IsGUID(lid))
            {
                if (session != null)
                {
                    if (session.SessionID != null)
                    {
                        if (session.SessionID.Length > 0)
                        {
                            var dr = new Discrepancy
                            {
                                lid = lid,
                                SessionId = session.SessionID,
                                IPAddress = Ops.Site.GetUserIP(HttpContext.Current),
                                UserId = "anonymous"
                            };
                            if (User != null)
                            {
                                if (User.Identity != null)
                                {
                                    if (User.Identity.IsAuthenticated)
                                    {
                                        dr.UserId = User.Identity.GetUserId();
                                    }
                                }
                            }
                            dr.ProblemTypeIds = ProblemTypes;
                            dr.ProblemTypeOther = ProblemTypeOther;
                            dr.idx = await DiscrepancyReportData.InsertDiscrepancyAsync(dr);
                            if (dr.idx > 0)
                            {
                                retval = "success";
                            }
                        }
                    }
                }
            }
        }


        return Ok(retval);
    }

jquery/javascript:

    $("#btnSendReport").bind('click', function (e) {
    var parElem = $(this).parent().parent().parent();
    var listID = parElem.find("#hidLID").val();
    var problemTypes = $.map(parElem.find('option:selected'), function (e) { return e.value; }).join(',');
    var problemTypeOther = parElem.find("#txtProblemTypeOther").val();

    var obj = {};
    obj.lid = listID;
    obj.ProblemTypes = problemTypes;
    obj.ProblemTypeOther = problemTypeOther;

    try {
        $.ajax({
            type: "POST",
            url: "../../api/reportdiscrepancy/",
            data: JSON.stringify(obj),     //not sure if this is necessary w/webAPI           
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var result = data; //not doing anything here
            },
            error: function (err) {
                console.log(err);
            }

        });
    } catch (err) {
        console.log(err);
    }

});

有人有想法么? WebAPI 2.1 沒有顯示 jQuery 帖子的示例(由於查詢字符串的限制,我不想使用 GET,而且我沒有使用 FORM 或 BODY,所以這些答案也不起作用)。 我研究得越多,我就會得到很多答案,但都是針對特殊情況的。 我只想看一個從 JQuery(3.x 或更高版本)到 MVC5(其他版本不同)而不是核心(完全不同)和 WebAPI 2 的 POST 和 OBJECT(不是字符串或任何簡單的東西)的工作示例。 X。 如何為 jquery 帖子(不是查詢字符串,不是表單)正確裝飾 controller。 有任何想法嗎?

通過添加〜來修復動作路線。 路線將從根開始

 [Route("~/api/reportdiscrepancy")]

修復 ajax url 也從根目錄開始。 還要刪除 stringify 和 contentType: "application/json; charset=utf-8",因為我不確定你的古老框架是否支持它

$.ajax({
            type: "POST",
            url: "/api/reportdiscrepancy",
            data: obj,         
            dataType: "json",

但我也會為一個動作創建一個特殊的 class

public class ViewModel
{
public string Lid {get; set;}
public string ProblemTypes {get; set; }
public string ProblemTypeOther {get; set;}
}

 [Route("~/api/reportdiscrepancy")]
public async Task<IHttpActionResult> ReportDiscrepancy(ViewModel model)
{
.....
}

在客戶端 - 我進行了 Serge 推薦的更改。

   $("#btnSendReport").bind('click', function (e) {
    var parElem = $(this).parent().parent().parent();
    var listID = parElem.find("#hidLID").val();
    var problemTypes = $.map(parElem.find('option:selected'), function (e) { return e.value; }).join(',');
    var problemTypeOther = parElem.find("#txtProblemTypeOther").val();
    if (problemTypeOther === null) { problemTypeOther = '' };

    var obj = {};
    obj.lid = listID;
    obj.ProblemTypes = problemTypes;
    obj.ProblemTypeOther = problemTypeOther;

    try {
        $.ajax({
            type: "POST",
            url: "../../api/reportdiscrepancy/",
            data: obj,
            dataType: "json",
            success: function (data) {
                var result = data; 
            },
            error: function (err) {
                console.log(err);
            }

        });
    } catch (err) {
        console.log(err);
    }

});

在 api controller 中,唯一需要更改的是 object 的輸入(webapi 2.x 會自動轉換 - 不知道)

      [Route("api/reportdiscrepancy")]
    [HttpPost]
    public async Task<IHttpActionResult> ReportDiscrepancy(DiscrepancyPost dp)
    {
        string retval = string.Empty;
        dp.lid = AppCore.Validation.StripToGUID(dp.lid);
        dp.ProblemTypes = AppCore.Validation.StripToDigitInCSVFromStr(dp.ProblemTypes);
        dp.ProblemTypeOther = AppCore.Validation.StripAllCharsForMetaTag(StripHtml(dp.ProblemTypeOther.xToStr()));
        var session = HttpContext.Current.Session;

        try
        {
            if (dp.lid.Length == 36 && dp.ProblemTypes.Length > 0 | dp.ProblemTypeOther.Length > 0)
            {
                if (IsGUID(dp.lid))
                {
                    if (session != null)
                    {
                        if (session.SessionID != null)
                        {
                            if (session.SessionID.Length > 0)
                            {
                                var dr = new Discrepancy
                                {
                                    lid = dp.lid,
                                    SessionId = session.SessionID,
                                    IPAddress = Ops.Site.GetUserIP(HttpContext.Current),
                                    UserId = "anonymous"
                                };
                                if (User != null)
                                {
                                    if (User.Identity != null)
                                    {
                                        if (User.Identity.IsAuthenticated)
                                        {
                                            dr.UserId = User.Identity.GetUserId();
                                        }
                                    }
                                }
                                dr.ProblemTypeIds = dp.ProblemTypes;
                                dr.ProblemTypeOther = dp.ProblemTypeOther;
                                dr.idx = await DiscrepancyReportData.InsertDiscrepancyAsync(dr);
                                if (dr.idx > 0)
                                {
                                    retval = "success";
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception)
        {
            //TODO logging
        }
        return Ok(retval);
    }

和 class:

 public class DiscrepancyPost
{
    public string lid { get; set; }
    public string ProblemTypes { get; set; }
    public string ProblemTypeOther { get; set; }
}

奇跡般有效。 所以問題出在 controller 簽名中(首先修復它並讓它在 Postman 中完美工作),然后在 jQuery 方面。

暫無
暫無

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

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