简体   繁体   English

ASP.NET Web API 2-如何过帐?

[英]ASP.NET Web API 2 - how to POST?

I've used scaffolding to generate a Controller class for Web API 2 in ASP.NET. 我已使用脚手架为ASP.NET中的Web API 2生成Controller类。

I'd like to post an object from a browser. 我想从浏览器发布对象。 This is the generated method running: 这是运行的生成方法:

    // POST: api/MyObjects
    [ResponseType(typeof(MyObject))]
    public async Task<IHttpActionResult> PostMyObject(MyObject myObject)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.MyObjects.Add(myObject);

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (MyObjectExists(myObject.Id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = myObject.Id }, myObject);
    }

I'm trying to invoke it from javascript/jquery: 我正在尝试从javascript / jquery调用它:

$.post("http://localhost:2239/api/UrlVisits/5", "=" + "something");

My question is, what do I put in for "something" to serialize it correctly? 我的问题是,我应该为"something"添加"something"以使其正确序列化? When the method is entered, myObject is a valid object with all fields set to null. 输入方法后, myObject是一个有效的对象,所有字段均设置为null。 I don't know where in the stack this serialization is happening, so I'm not sure how to modify my post to fix it. 我不知道该序列化发生在堆栈中的什么地方,所以我不确定如何修改我的post以进行修复。

You need to change up the structure a bit. 您需要稍微改变一下结构。

First, /5 signifies an ID of 5, which doesn't make sense with the compound object your method is expecting. 首先,/ 5表示ID为5,这与您的方法所期望的复合对象没有任何意义。

Second, you don't need to manually specify any URL parameterization with "=". 其次,您无需使用“ =”手动指定任何URL参数化。 Both jQuery and WebAPI will handle those pieces for you if you structure your object correctly. 如果正确构造对象,jQuery和WebAPI都将为您处理这些部分。 WebAPI 2 is significantly more powerful when it comes to deserializing complex objects than it's predecessor. 当反序列化复杂对象时,WebAPI 2的功能要比其前身强大得多。 Simply post the object. 只需发布对象。

$.post("http://localhost:2239/api/UrlVisits", {id:1, name:"test name"});

Finally, you can use the [FromBody] attribute to specify that your object will be posted on the form body. 最后,您可以使用[FromBody]属性来指定您的对象将被发布在表单主体上。

[ResponseType(typeof(MyObject))]
public async Task<IHttpActionResult> PostMyObject([FromBody]MyObject myObject)

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

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