Web API POST方法

时间:2017-08-17 14:28:40

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

路线配置

The provided property key is not in the database
One of the property names in your query is not available in the database, make sure you didn't misspell it or that the label is available when you run this statement in your application (the missing property name is: host)

发表-方式

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

我试图发布一些数据,如屏幕截图所示

Postman

我得到一个错误

[HttpPost] public Probabilities Post(string word, string userId) { Request request = new Request(); request.Identify(word, userId); Probabilities probabilities = probabilitiesFactory.GetBy(request.ProbabilitiesId, "Id"); return probabilities; }

发生了什么事?如何发布2个简单的字符串并获得结果

2 个答案:

答案 0 :(得分:1)

虽然不是强制性的,但您应该遵循良好做法并将有效负载封装到模型中。

public class MyModel {
    public sting word { get; set; }
    public sting userId { get; set; }
}

然后,您可以使用FromBody参数属性将模型绑定到发送的数据。

最后解决资源未找到的问题,确保控制器遵循正确的约定,因为OP配置了基于约定的路由。

public class IdentificationController : ApiController {

    [HttpPost]
    public Probabilities Post([FromBody] MyModel model) {
        string word = model.word;
        string userId = model.userId;
        Request request = new Request();
        request.Identify(word, userId);
        Probabilities probabilities = probabilitiesFactory.GetBy(request.ProbabilitiesId, "Id");
        return probabilities;
    }
}

Reference: Parameter Binding in ASP.NET Web API

Reference: Routing in ASP.NET Web API

答案 1 :(得分:1)

此问题有2种不同的解决方案。 的第一worduserId发送为QueryStrings ..这是一个例子:

http://localhost/api/identification?word=hey&&userId=12

这将适用于您的情况,因此您不需要更改代码中的任何内容。

最后我最喜欢的解决方案: 创建一个这样的模型类:

public class IdentificationModel{
    public string word { get; set; }
    public string userId { get; set; }
}

然后将它作为参数对象,如下所示:

[HttpPost]
public Probabilities Post(IdentificationModel requestModel) {
    Request request = new Request();
    request.Identify(requestModel.word, requestModel.userId);
    Probabilities probabilities = probabilitiesFactory.GetBy(request.ProbabilitiesId, "Id");
    return probabilities;
}

最后一个不需要添加[FromBody]属性,因为任何类对象都是api方法,将自动等待为Request Body Object。