【发布时间】:2019-03-02 10:50:02
【问题描述】:
我将 web api 添加到可用的项目中。 我的 api 控制器:
namespace MyApplication.Controllers
{
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult Create(string UserName, string Password, string DoingDateTime, int ReferenceFrom, int ReferenceTo, string MaturityDateTime = "", int? PersonCompany_AffiliationID = null, int? SubjectID = null, string Description = "", int? ImportanceDegreeID = null, int? StatusID = null, int CompletionPercentage = 0, int? DossierID = null)
{
...
return Ok();
}
}
}
WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
将以下代码添加到 web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
和 ajax:
$.ajax({
url: 'localhost:3641/api/TaskApi',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: {
UserName: 'admin',
Password: '123',
Description: 'test',
DoingDateTime: '1397/12/10',
ReferenceFrom: 2,
ReferenceTo: 2
},
type: 'Post',
success: function (data) {
alert('success');
}
, error: function (response) {
alert(response.responseText);
}
});
当我在浏览器中测试 web api 时:
它工作正常。但是当aun ajax返回错误并且response.responseText返回“未定义”。
【问题讨论】:
-
如果您在正文中设置参数,您应该期望 WebApi 中有一个带有 FromBody-Attribute 的对象。
-
@Nikolaus:我将操作更改为:public IHttpActionResult PostNewTask([FromBody] string UserName, [FromBody] string Password, [FromBody] string DoingDateTime, [FromBody] int ReferenceFrom, [FromBody] int ReferenceTo, [FromBody] string MaturityDateTime = "", [FromBody] int? PersonCompany_AffiliationID = null, [FromBody] int? SubjectID = null, [FromBody] string Description = "", [FromBody] int? ImportanceDegreeID = null, [FromBody] int? StatusID = null, [FromBody] int CompletionPercentage = 0, [FromBody] int?DossierID = null) 但仍然返回“未定义”错误
-
@Miss 你不能有多个[FromBody]。这条规则的reason 是请求正文可能存储在只能读取一次的非缓冲流中。跨度>
-
你在使用 Visual Studio 吗?
-
@Nikolaus:是的
标签: ajax asp.net-mvc asp.net-web-api2