简体   繁体   English

如何在Web API中绑定模型(例如在MVC中发生)?

[英]How to bind model in web api (like happen in mvc)?

My Html code is something like this. 我的HTML代码是这样的。

<input type="text" name="Id" value="123"/>
<input type="text" name="Name" value="XYZ"/>
<input type="text" name="Abc.Address" value="ABC,XYZ 700567"/>
<input type="text" name="Abc.Mobile" value="6958743216"/>

Classes:- 班级:-

class A
{
    public string Id { get; set; }
    public string Name { get; set; }
    public Abc Abc { get; set; }
}

class Abc
{
    public string Address { get; set; }
    public string Mobile{ get; set; }
}

Through upper input When I am calling MVC controller the then binding happen. 通过上层输入当我调用MVC控制器时,将发生绑定。 means for following method 以下方法的意思

public ActionResult Post(A x)

value in x is x中的值为

x.Id="123"
x.Name="XYZ"
x.Abc.Address="ABC,XYZ 700567"
x.Abc.Mobile="6958743216"

but when I tried same things in web api it is giving me 415(Unsupported media type). 但是当我在Web api中尝试相同的操作时,它却给我415(不受支持的媒体类型)。 means for following method 以下方法的意思

public IHttpActionResult Post(A x)

instead of binding it is giving 415 status code saying Unsupported Media Type. 而不是绑定,而是给出415状态代码,表示不支持的媒体类型。 I know it is stupid to ask but why this happen? 我知道问这个问题很愚蠢,但是为什么会这样呢? and if I want to do same binding as happen in mvc how can I achieve that?(I don't want to do something like this --> public IHttpActionResult Post([SomeBinder]A x) ) 如果我想做与mvc中相同的绑定,我该如何实现呢?(我不想做这样的事情-> public IHttpActionResult Post([SomeBinder]A x)

Is there way to achieve this or Not? 有没有办法做到这一点?

It has to do with the Content-Type of the request. 它与请求的Content-Type有关。

Your WebAPI endpoint is expecting your post request to have the Content-Type application/json . 您的WebAPI端点期望您的发布请求具有Content-Type application/json Once you add that it will be accepted. 一旦添加,它将被接受。

However if you want to post an HTML form to a controller you shouldn't use WebAPI. 但是,如果要将HTML表单发布到控制器,则不应使用WebAPI。 If you have to then you can serialize the form and submit the form using javascript 如果需要,则可以序列化表单并使用javascript提交表单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM