首页 > 解决方案 > ASP Web API Ajax 发布请求 HTTP 错误 415

问题描述

我正在尝试从 ASP.NET 学习 Web API,并想做一个小待办事项列表。

所有工作都大摇大摆,但如果我想在 ajax 中进行发布请求,我会收到“415 Unsupported Media Type”错误。

我的 Ajax 调用:

function sendTodoTitle() {
            $.ajax({
               url: url + "/api/todo/sendTitle",
               type: "POST",
               dataType: "JSON",
               data: JSON.stringify({todoItem: textIn.val()}),
               success: function(data) {
                   valData(data);
               }
            });
        } 

url 确实有效,所以这不是因为 url 的问题。textIn 也可以正常工作。(一个 )

我的控制器:

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase {
    InFSTodo fs = new InFSTodo();

    [HttpPost]
    public ActionResult<String> Post() {
        return Ok(fs.GetJSON());
    }

    [HttpPost("sendTitle")]
    public ActionResult<String> Post([FromBody] String todoItem) {
        var list = fs.Get();
        list.Add(new Todo(list.Count, todoItem));
        fs.Store(list);

        return Ok(list.ToJson());
    }

从以前在这里提出的问题中,我得到了以下信息:

我希望有人可以在这里帮助我,因为我已经尝试了整整一天半,感谢您的帮助!

编辑:

InFSTodo.cs:

 public class InFSTodo {
    string fileName = "todo.json";

    /// <summary>
    /// Store the JSON in file
    /// </summary>
    /// <param name="list">The list of todos to be stored</param>
    public void Store(List<Todo> list) {
        string json = list.ToJson(); // ToJson() <-- Extension Method

        if (!File.Exists(fileName))
            File.CreateText(fileName).Close();

        StreamWriter sw = new StreamWriter(fileName);
        sw.Write(json);
        sw.Flush();
        sw.Close();
    }

    /// <summary>
    /// Get the JSON from file and convert to List of todos
    /// </summary>
    /// <returns>List of todos</returns>
    public List<Todo> Get() {
        if (!File.Exists(fileName))
            return new List<Todo>();

        StreamReader sr = new StreamReader(fileName);
        string json = "";

        while(sr.Peek() != -1) 
            json += sr.ReadLine();

        sr.Close();

        return ListExtension.FromJSON(json); // <-- No possibillity for static Extension Methods
    }

    /// <summary>
    /// Get the JSON from file
    /// </summary>
    /// <returns>JSON as string</returns>
    public String GetJSON() {
        return Get().ToJson();
    }
}

TodoController.cs:

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase {
    InFSTodo fs = new InFSTodo();

    [HttpPost]
    public ActionResult<String> Post() {
        return Ok(fs.GetJSON());
    }

    [HttpPost("sendTitle")]
    public ActionResult<String> Post(String todoItem) {
        var list = fs.Get();
        list.Add(new Todo(list.Count, todoItem));
        fs.Store(list);

        return Ok(list.ToJson());
    }

    [HttpPost("deleteTodo")]
    public ActionResult<String> Post(int id) {
        var list = fs.Get();
        list.Remove(list.Find(item => item.Id == id));
        fs.Store(list);

        return Ok(list.ToJson());
    }

    [HttpGet("{id}")]
    public ActionResult<String> PostDone(int id) {
        var list = fs.Get();
        var todo = list.Find(item => item.Id == id);

        if (todo != null)
            todo.WasDone = true;
        else
            return StatusCode(422); // 422 Unprocessable Entity

        fs.Store(list);

        return Ok(list.ToJson());
    }
}

待办事项.cs:

[Serializable]
public class Todo {
    public int Id { get; private set; }
    public String Title { get; set; }
    public bool WasDone { get; set; }

    public Todo(int id, String title) {
        Id = id;
        Title = title;
        WasDone = false;
    }

    public void ChangeID(Todo second) {
        int id = Id;
        Id = second.Id;
        second.Id = id;
    }
}

Serge回复后的错误信息:

在此处输入图像描述

邮递员的错误:

在此处输入图像描述

标签: asp.netajaxwebasp.net-web-api

解决方案


试试这个ajax

function sendTodoTitle() {
            $.ajax({
               url: url + "/api/todo/sendTitle",
               type: "POST",
               data: {todoItem: textIn.val()},
               success: function(data) {
                   valData(data);
               }
            });
        } 

并删除 [FromBody]

[HttpPost("sendTitle")]
 public ActionResult<String> Post( string todoItem) {

推荐阅读