我开始使用 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 中获取简单类型,如 int
、string
等。您需要使用 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/