ASP.NET Core WebApi [英] ASP.NET Core WebApi

查看:399
本文介绍了ASP.NET Core WebApi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的.NET Core制作网络API。但是在使用 [HttpPost] 时遇到了一些麻烦。当我使用邮递员时,它不会返回任何东西。同样,当我在返回行上放置断点时,它也永远不会命中。

I'm trying to make a web api using the new .NET Core. But having some trouble using the the [HttpPost]. When I use postman, it doesn't return anything. Also when I put a breakpoint on the return line it's never hit.

这是我在控制器中的方法:

This is my method in the controller:

    // POST api/values
    [HttpPost]
    public IEnumerable<string> Post([FromBody]string value)
    {
        return new string[] { "value1", "value2" };
    }

GET方法有效:

    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    } 

它返回一个Json值,当我放置一个断点时就会命中。

It returns a Json value and when I place a breakpoint it hits.

我想我必须在其他地方添加一些内容才能将帖子映射到此方法,但我不知道是什么。

I think I have to add something somewhere else to map the post to this method, but I can't figure out what.

这是在邮递员中生成的邮政编码:

This is the Post code generated in Postman:

POST /api/values HTTP/1.1
Host: localhost:60228
Content-Length: 0
Cache-Control: no-cache
Postman-Token: 295f7c89-f5a8-d6cd-d679-ae907b010550

firstName:jantje


推荐答案

尝试将JSON数据发布到控制器操作中,并使用模型类绑定值。我假设默认字符串不能由ASP.NET Core默认使用的JSON或XML格式化程序解析。

Try to post JSON data to your controller action and use a model class to bind the values. I assume the simple string cannot be parsed by the JSON or XML formatters that are used by ASP.NET Core by default.

所以这可能行得通:

[HttpPost]
public IActionResult Post([FromBody]DataModel model)
{
    return Ok();
}

public class DataModel {
     public string FirstName {get; set;}
}

带有此JSON数据

{
    firstName: "jantje"
}

这篇关于ASP.NET Core WebApi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆