【问题标题】:Ajax call to a ASP.NET MVC web API对 ASP.NET MVC Web API 的 Ajax 调用
【发布时间】:2013-11-28 22:54:51
【问题描述】:

我正在开发一个 MVC 应用程序,并且正在尝试与我拥有的 Web API 控制器建立 AJAX 连接。我能发现的唯一错误是“身份不明”。此外,在我的 api 控制器删除操作中,我抛出了一个随机异常,因此我可以检测我是否成功进入该方法,但我没有。

更新:

好的,我似乎在 ajax 调用中忘记了我的 url 上的“removeFile”路由,但问题是如果我在 ajax 调用中添加“data”属性以传递我的序列化表单控件,它将停止正常工作。

数据:$("#frmManipulate").serialize()

Ajax 调用:

$("#frmManipulate").submit(function () {
        if (confirm("Are you sure you want to delete all selected files?")) {
            if ($(this).data('clicked').is('[name="delete"]')) {
                $.ajax({
                    type: "DELETE",
                    url: "api/file/removeFile",
                    data: $("#frmManipulate").serialize()
                }).complete(function ($data) {
                    alert("done");
                });
        }
        return false;
    });

Web API 控制器:

[RoutePrefix("api/file")]
public class ManipulateController : ApiController
{
    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    [Route("removeFile")]
    // DELETE api/<controller>/5
    public void DeleteFile(string[] url)
    {
        foreach (var file in url)
        {
            throw new MarshalDirectiveException();
        }
    }
}

【问题讨论】:

    标签: asp.net-mvc jquery asp.net-web-api


    【解决方案1】:

    尝试在没有消息正文的情况下发出 DELETE 请求。

    【讨论】:

    • 我试过了,但没用。无论哪种方式,我都想将表单控件传递给它。
    • 尝试将 [HttpDelete] 属性添加到控制器方法中,然后尝试执行删除请求
    • DELETE 不能有邮件正文。
    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 2020-08-04
    • 1970-01-01
    • 2016-02-08
    • 2021-09-16
    • 1970-01-01
    • 2020-07-07
    • 2012-07-27
    相关资源
    最近更新 更多