【问题标题】:Creating post web api 2 actions创建发布 web api 2 操作
【发布时间】:2015-11-01 15:07:40
【问题描述】:

我目前正在尝试做一些应该相当直截了当的事情,但老实说,目前离它还很远,这让我有点生气。

我一直在我的 WebApi 中使用 Get 操作,但是我正在尝试创建 Post 操作以保持我的 mvc 控制器清洁但是我无法终生弄清楚为什么我的 get 操作按预期工作但我的发布操作导致 404

using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using TamWeb.Models.api;

namespace TamWeb.Controllers.api
{
    [Authorize]
    [Route("api/[controller]")]
    public class AdminController : Controller
    {
        [HttpPost]
        public bool UpdateDetails([FromBody]DetailsViewModel model)
        {
            return false;
        }
    }
}

using System;

namespace TamWeb.Models.api
{
    public class DetailsViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

api 控制器非常简单,根据其他几个 api 问题而不是使用字符串参数,我创建了一个模型对象并遵循其他答案以及我能找到的一些过时的文档我使用了 api如下:

$(function() {
    var firstname = $('#firstName').val();
    var lastname = $('#lastName').val();

    $.ajax({
        url: "api/admin/UpdateDetails",
        type: "POST",
        data: JSON.stringify([firstname, lastname]),
        success: function(data) {
            console.log(data);
        },
        error: function() { console.log("error") }
    });
});

据我所知,一切“应该”工作,但是提琴手一直告诉我网址不存在,所以现在我不知道出了什么问题。

【问题讨论】:

  • 你试过url: "api/admin"吗?

标签: asp.net-web-api2 asp.net-core-mvc asp.net-web-api-routing


【解决方案1】:

希望我的回答可以帮助您处理您的问题。
1.第一个问题你必须使用“ApiController”而不是“Controller”
2. [Authorize]

如下代码,我将简单的代码分享给你,我希望它可以解决你的问题 客户端代码

$("#read1").click(function () {    
      $.support.cors = true;
      $.ajax({
          crossDomain: true,
          url: 'http://localhost:43520/api/Banners/',
          datatype: "json",
          contenttype: "application/json; charset=utf-8",
          data: { id: 123 },
          type: 'post',          
          error: function (xhr, status, errorThrow) {
              alert(xhr.status);
          },
          success: function (data) {
              alert(JSON.stringify(data));
          }
      });
  });

服务器代码

 // GET: api/Banners/5
        [ResponseType(typeof(Banners))]
        public IHttpActionResult GetBanners(int id)
        {
            Banners banners = db.Banners.Find(id);
            if (banners == null)
            {
                return NotFound();
            }

            return Ok(banners);
        }

【讨论】:

    猜你喜欢
    • 2012-07-04
    • 2017-07-22
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多