一个控制器中的多个 HttpPost 方法在 Web 中不起作用 Api

More than one HttpPost Method in one Controller not working in Web Api

我有一个 Web Api 项目,首先我用一个 HttpPost 方法创建了一个控制器,然后它工作正常。但是当我添加另一个 HttpPost 方法时,没有人在工作,但是当我删除任何一个时,另一个方法在工作。我的代码是。

Web Api 控制器:

 public class ForumPost
    {
        public int ProjectId { get; set; }
        public int CourseId { get; set; }
        public int SubjectId { get; set; }
        public int TopicId { get; set; }
        public int ContentId { get; set; }
        public string Heading { get; set; }
        public string Description { get; set; }
        public int UserId { get; set; }          
    }

    [HttpPost]
    [ActionName("AddForumPost")]
    public string AddForumPost([FromBody]ForumPost _ForumPost)
    {
        string strResult = "N";
        using (ICA.LMS.Service.Models.Entities db = new Entities())
        {

        }
        return strResult;
    }

    public class Comment
    {
        public int ForumId {get;set;}
        public string Response { get; set; }
        public int ParentId { get; set; }
        public int LevelId { get; set; }
        public string CreatedBy { get; set; }
    }

    [HttpPost]
    [ActionName("AddComment")]
    public string AddComment([FromBody]Comment cmt)
    {
        string strResult = "N";
        using (ICA.LMS.Service.Models.Entities db = new Entities())
        {

        }
        return strResult;
    }    

Jquery 呼叫:

var comment = { ForumId: fId, Response: res, ParentId: pId, LevelId: lId, CreatedBy: uId };

jQuery.support.cors = true;
$.ajax({        
    url: 'http://localhost:1900/api/ForumApi',
    type: 'Post',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data:comment,
    dataType: 'json',
    async: false,
    success: function (data) {
        var efId = $('#EncForumId').val();
        if (data == "Y")
            location.replace('../Forum/ForumDiscussion?id=' + efId);
        else
            myAlert('Unable to Post. Try again!');
    },
    error: function (e) {
        myAlert(JSON.stringify(e));
    }
});

错误:-

**{"readyState":0,"status":0,"statusText":"NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:1900/api/ForumApi'."}**

默认情况下,web api 路由是这个

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

您会注意到路线中没有任何动作。

网络api根据HTTP Verb和动作名称选择动作。您可以保留操作名称 POST 或使用注释 HttpPost 或保留以 POST (PostComment)

开头的操作名称

为了克服这个问题,如果你必须通过动作名称来路由,你必须像这样添加一个新路由

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

现在,任何匹配 api/{controller}/{action}/{id} 模式的请求都将被此路由捕获,并将传递给相应的操作。

您可以阅读更多相关内容 here 此外,您现在必须更改您正在调用的网址,以便它们与新添加的路线相匹配 从 http://localhost:1900/api/ForumApihttp://localhost:1900/api/ForumApi/AddForumPost 和其他 url 一样明智