【发布时间】:2020-02-29 03:51:24
【问题描述】:
我正在尝试从 Angular 应用程序更新我的资源,使用 PUT 方法进行 Web Api 调用。出于某种原因,我收到的只是 400 Bad Request 错误,即使我尝试使用 Postman 做同样的事情。
因此我有两个问题,第一个 - 如果以下代码正确,考虑到 web.config 文件和控制台输出,第二个 - 我应该以某种方式配置我的 IIS 以允许 PUT 调用吗?一切都在 IIS 上运行,到目前为止,我在解决这个问题时遇到了 blogpost,其中提到了这样的事情——我真的不知道应该改变什么。因为在我看来,我已经在 web.config 中删除了 WebDAV。
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
<remove name="WebDAV" />
</handlers>
<aspNetCore processPath=".\AuctorAPI.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</location>
</configuration>
我的角度服务中的更新方法:
updateClient(client: any) {
console.log(client);
var obj = JSON.parse(client);
const headers = new HttpHeaders().set('content-type', 'application/json');
var body = {
name: obj['name'],
surname: obj['surname'],
phone: obj['phone'],
email: obj['email'],
gymEntriesLeft: obj['gymEntriesLeft'],
martialArtsEntriesLeft: obj['martialArtsEntriesLeft']
}
console.log("ID");
console.log(obj['id']);
console.log("BODY");
console.log(JSON.stringify(body));
return this.http.put<Client>(this.url + obj['id'], JSON.stringify(body), { headers }).pipe(
catchError(this.errorHandler)
);
}
Angular 组件(调用删除方法)
onFormSubmit() {
this.clientService.updateClient( this.clientById).subscribe(() => {
this.getClients();
this.edit = false;
this.editRowId = null;
})
}
控制器方法:
// PUT: api/Clients/5
[HttpPut("{id}")]
public async Task<IActionResult> PutClient(int id, Client client)
{
if (id != client.Id)
{
return BadRequest();
}
_context.Entry(client).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClientExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
【问题讨论】:
-
如果在您的操作中应用
[FromRoute]到id和[FromBody]到client参数会怎样?或者将[ApiController]属性应用于控制器? -
FromRoute/FromBody 和 ApiController 都没有帮助
-
如果您尝试创建 POST 端点怎么办?如果您将服务作为控制台应用程序而不是 IIS 运行呢?
-
@AndriiLitvinov 但如何?你的意思是用 post 代替 put ,然后保持现在的状态?
-
是的,或者在控制器中创建另一个动作。只是看看问题是在 IIS 中的 PUT 方法配置还是应用程序或客户端的问题。
标签: c# angular asp.net-web-api postman