javascript - 将字符串从 javascript 代码发布到服务器上的 ApiController

标签 javascript c# asp.net-mvc post

我开始使用 ASP.NET Web API。当我像接下来那样在 Controler 中获取我的实体时,我想知道序列化功能:

public class EntitiesController : ApiController
{
    [Queryable]
    public IEnumerable<Entity> Get()
    {
        return m_repository.GetAll();
    }
    public HttpResponseMessage Post(Entity entity)
    {
        if (ModelState.IsValid)
        {
            m_repository.Post(entity);
            var response = Request.CreateResponse<Entity>(HttpStatusCode.Created, entity);
            return response;
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

在 JavaScript 方面:

// create new entity.
$.post("api/entities", $(formElement).serialize(), "json")
    .done(function (newEntity) { self.contacts.push(newEntity); });

但我不需要实体。我想接收字符串。所以我以下一种方式更改了 Controller :

public class EntitiesController : ApiController
{
    [Queryable]
    public IEnumerable<string> Get()
    {
        return m_repository.GetAll();
    }
    public HttpResponseMessage Post(string entity)
    {
        if (ModelState.IsValid)
        {
            m_repository.Post(entity);
            var response = Request.CreateResponse<Entity>(HttpStatusCode.Created, entity);
            return response;
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

我尝试了不同的dataType ("json", "text", "html") post function .和不同的 data 表示 $(formElement).serialize(), "simple Text", jsonObject, JSON.stringify(jsonObject)。但我总是在服务器端得到 null 作为 Post 操作中的 entity 参数。

我做错了什么?

最佳答案

如果您想将表单数据作为字符串发布,您需要做两件事:

默认情况下,Web API 尝试从请求 URI 中获取简单类型,如 intstring 等。您需要使用 FromBody 属性告诉 Web API 从请求正文中读取值:

public HttpResponseMessage Post([FromBody]string entity)
{
   //...
}

并且您需要使用空键发布您的值:

$.post("api/entities", { "": $(formElement).serialize() }, "json")
    .done(function (newEntity) { self.contacts.push(newEntity); });

您可以阅读有关此 Web.API 教程文章的更多信息:Sending HTML Form Data

关于javascript - 将字符串从 javascript 代码发布到服务器上的 ApiController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15958114/

相关文章:

PHP + JavaScript 弹出窗口

c# - 从集合中删除项目的最佳方法

javascript - 为什么我的 jQuery.post() ajax 在我返回一个 View 时失败,但在我返回另一个 View 时却没有失败?

c# - 将 Wyam 嵌入到 asp.net core MVC 解决方案中的正确方法是什么?

javascript - 如何检测后面没有另一个换行符的换行符?

javascript - 单击一个按钮然后显示选定的值

javascript - 单击下拉菜单时更新表格单元格内容

c# - 在 C# 中使用没有字节顺序标记 (BOM) 的 UTF-16 编码保存文本文件?

c# - 为什么我在执行 HTTP POST 时用完了流的字节数?

asp.net-mvc - ASP.NET MVC 和 Unity 1.2 容器问题