Web API Put Request가 Http 405 Method Not Allowed 오류를 생성합니다.
전화 드리겠습니다.PUTmethod on my Web API - method의 세 번째 줄(ASP에서 Web API를 호출합니다).NET MVC 프론트 엔드:

client.BaseAddress이http://localhost/CallCOPAPI/.
여기 있습니다contactUri:

여기 있습니다contactUri.PathAndQuery:

마지막으로 405에 대한 답변은 다음과 같습니다.

웹 API 프로젝트의 WebApi.config는 다음과 같습니다.
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApiGet",
routeTemplate: "api/{controller}/{action}/{regionId}",
defaults: new { action = "Get" },
constraints: new { httpMethod = new HttpMethodConstraint("GET") });
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
난 그 길을 없애보려고 노력했어PutAsJsonAsync로.string.Format("/api/department/{0}", department.Id)그리고.string.Format("http://localhost/CallCOPAPI/api/department/{0}", department.Id)운도 없이
왜 405 오류가 발생하는지 아는 사람 있나요?
갱신하다
요청에 따라 부문별 컨트롤러 코드(프런트엔드 프로젝트의 부문별 컨트롤러 코드와 WebAPI의 부문별 API 컨트롤러 코드를 모두 게시합니다).
프론트 엔드 부문 컨트롤러
namespace CallCOP.Controllers
{
public class DepartmentController : Controller
{
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
Uri contactUri = null;
public DepartmentController()
{
// set base address of WebAPI depending on your current environment
client.BaseAddress = new Uri(ConfigurationManager.AppSettings[string.Format("APIEnvBaseAddress-{0}", CallCOP.Helpers.ConfigHelper.COPApplEnv)]);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
// need to only get departments that correspond to a Contact ID.
// GET: /Department/?regionId={0}
public ActionResult Index(int regionId)
{
response = client.GetAsync(string.Format("api/department/GetDeptsByRegionId/{0}", regionId)).Result;
if (response.IsSuccessStatusCode)
{
var departments = response.Content.ReadAsAsync<IEnumerable<Department>>().Result;
return View(departments);
}
else
{
LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
"Cannot retrieve the list of department records due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
return RedirectToAction("Index");
}
}
//
// GET: /Department/Create
public ActionResult Create(int regionId)
{
return View();
}
//
// POST: /Department/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int regionId, Department department)
{
department.RegionId = regionId;
response = client.PostAsJsonAsync("api/department", department).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Edit", "Region", new { id = regionId });
}
else
{
LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
"Cannot create a new department due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
return RedirectToAction("Edit", "Region", new { id = regionId });
}
}
//
// GET: /Department/Edit/5
public ActionResult Edit(int id = 0)
{
response = client.GetAsync(string.Format("api/department/{0}", id)).Result;
Department department = response.Content.ReadAsAsync<Department>().Result;
if (department == null)
{
return HttpNotFound();
}
return View(department);
}
//
// POST: /Department/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int regionId, Department department)
{
response = client.GetAsync(string.Format("api/department/{0}", department.Id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.PutAsJsonAsync(string.Format(contactUri.PathAndQuery), department).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index", new { regionId = regionId });
}
else
{
LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
"Cannot edit the department record due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
return RedirectToAction("Index", new { regionId = regionId });
}
}
//
// GET: /Department/Delete/5
public ActionResult Delete(int id = 0)
{
response = client.GetAsync(string.Format("api/department/{0}", id)).Result;
Department department = response.Content.ReadAsAsync<Department>().Result;
if (department == null)
{
return HttpNotFound();
}
return View(department);
}
//
// POST: /Department/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int regionId, int id)
{
response = client.GetAsync(string.Format("api/department/{0}", id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.DeleteAsync(contactUri).Result;
return RedirectToAction("Index", new { regionId = regionId });
}
}
}
웹 API 부서 API 컨트롤러
namespace CallCOPAPI.Controllers
{
public class DepartmentController : ApiController
{
private CallCOPEntities db = new CallCOPEntities(HelperClasses.DBHelper.GetConnectionString());
// GET api/department
public IEnumerable<Department> Get()
{
return db.Departments.AsEnumerable();
}
// GET api/department/5
public Department Get(int id)
{
Department dept = db.Departments.Find(id);
if (dept == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return dept;
}
// this should accept a contact id and return departments related to the particular contact record
// GET api/department/5
public IEnumerable<Department> GetDeptsByRegionId(int regionId)
{
IEnumerable<Department> depts = (from i in db.Departments
where i.RegionId == regionId
select i);
return depts;
}
// POST api/department
public HttpResponseMessage Post(Department department)
{
if (ModelState.IsValid)
{
db.Departments.Add(department);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, department);
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// PUT api/department/5
public HttpResponseMessage Put(int id, Department department)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
if (id != department.Id)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
db.Entry(department).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// DELETE api/department/5
public HttpResponseMessage Delete(int id)
{
Department department = db.Departments.Find(id);
if (department == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Departments.Remove(department);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK, department);
}
}
}
Windows 기능을 체크하고 WebDAV라고 하는 것이 인스톨 되어 있지 않은 것을 확인했습니다만, 인스톨 되어 있지 않다고 되어 있었습니다.어쨌든 다음 내용을 web.config(프런트엔드와 WebAPI 모두)에 배치했습니다.이것으로 동작합니다.이거 안에 넣었어요.<system.webServer>.
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
또한 많은 경우 다음 항목을 에 추가해야 합니다.web.config핸들러에 있습니다.바박 덕분에
<handlers>
<remove name="WebDAV" />
...
</handlers>
WebDav-SchmebDav......ID로 URL을 올바르게 생성했는지 확인합니다.http://www.fluff.com/api/Fluff?id=MyID,처럼 보내지 말고 http://www.fluff.com/api/Fluff/MyID처럼 보내.
예.
PUT http://www.fluff.com/api/Fluff/123 HTTP/1.1
Host: www.fluff.com
Content-Length: 11
{"Data":"1"}
이건 아주 잠깐동안 날 힘들게 했어, 완전 창피했어.
이 항목을 에 추가합니다.web.configIIS에 알려야 할 것은PUT PATCH DELETE그리고.OPTIONS수단. 그리고 어느 쪽인가.IHttpHandler호출할 수 있습니다.
<configuation>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</configuration>
또한 WebDAV가 활성화되어 있지 않은지 확인합니다.
ASP를 실행하고 있습니다.IIS 8.5의 NET MVC 5 응용 프로그램입니다. 여기에 게시된 모든 변형을 시도해보니 다음과 같습니다.web.config외관:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
관리자 권한이 없어서 서버에서 WebDav를 제거할 수 없습니다.그리고 가끔씩은 제가 받은 게method not allowed.css 및 .closs 파일에 저장되어 있습니다.마지막으로 위의 설정을 통해 모든 것이 다시 작동하기 시작했습니다.
[From Body]에서 액션 패럴 중 하나를 장식하면 문제가 해결되었습니다.
public async Task<IHttpActionResult> SetAmountOnEntry(string id, [FromBody]int amount)
단, ASP.방법 파라미터에 복잡한 오브젝트가 사용되는 경우 NET은 올바르게 추론한다.
public async Task<IHttpActionResult> UpdateEntry(string id, MyEntry entry)
이 문제의 또 다른 원인은 "id"에 기본 변수 이름(실제로 id)을 사용하지 않는 것입니다.
이 경우 루트("api/images")가 같은 이름의 폴더("~/images")와 충돌하여 정적 핸들러에 의해 오류 405가 호출되었습니다.
IIS 의 GUI 의 Webdav 의 Webdav 의 설정.
1)Goto .1) II 를 1 1 1 1 1 1 。
2) 해 2 2 2 2 2 2 2 2 2 2 2 2 2 2.
[맵핑] 3) [핸들러 맵핑]을 엽니다.
module.4) WebDav 모듈을 합니다.마우스 오른쪽 버튼을 클릭하여 삭제합니다.
참고: 웹 앱의 web.config도 업데이트됩니다.
이 간단한 문제가 진짜 두통을 일으킬 수 있어요!
요.EDIT )PUT) 는 a) id 및 b) 오브젝트의 상정하고 메서드는 a) int id 및 b) 부문 오브젝트의 2개의 파라미터를 상정하고 있습니다.
VS > 읽기/쓰기 옵션을 가진 add 컨트롤러에서 이 코드를 생성할 때의 기본 코드입니다.단, 2개의 파라미터를 사용하여 이 서비스를 소비해야 합니다.그렇지 않으면 에러 405가 발생합니다.
id의 .PUT… 몇 시간 동안 눈치채지 못했는데!설정을 필요에 따라서 변경하지 않는 한, ID 로서 이름을 유지할 필요가 있습니다.
클라이언트 응용 프로그램과 서버 응용 프로그램은 동일한 도메인에 있어야 합니다.다음은 예를 제시하겠습니다.
client - localhost
server - localhost
다음 중 하나가 아닙니다.
클라이언트 - localhost:21234
server - localhost
언급URL : https://stackoverflow.com/questions/19162825/web-api-put-request-generates-an-http-405-method-not-allowed-error
'programing' 카테고리의 다른 글
| WaitUntilAllTasksAreFinished 오류 Swift (0) | 2023.04.04 |
|---|---|
| wp-rest api 응용 프로그램에서 wordpress nonce를 사용할 수 없습니다. (0) | 2023.04.04 |
| 치명적인 오류:허용된 메모리 크기 268435456바이트가 모두 사용됨(71바이트 할당 시도) (0) | 2023.04.04 |
| Google의 폴리머는 다른 프런트 엔드 프레임워크를 보완하거나 보완하기 위한 완전한 기능을 갖춘 프런트 엔드 프레임워크입니까? (0) | 2023.04.04 |
| React.useState는 소품에서 상태를 새로고침하지 않습니다. (0) | 2023.04.04 |