기존 MVC 웹 응용 프로그램에 웹 API를 추가한 후 404 오류 발생
여기에 훌륭한 질문이 있습니다. 기존 ASP.NET MVC 4 웹 애플리케이션 프로젝트에 웹 API를 추가하는 방법은 무엇입니까?
불행하게도, 그것은 제 문제를 해결하기에 충분하지 않았습니다.저는 제가 잘못한 것이 없는지 확인하기 위해 두 번이나 노력했습니다."Controllers"를 마우스 오른쪽 버튼으로 클릭하고 모델 클래스와 DB 컨텍스트를 선택한 "Entity Framework를 사용하는 Web API 2 Controller with actions" 항목을 추가했습니다.모든 게 잘 풀렸어요하지만 여전히.../api/Rest에 액세스하려고 할 때마다 404 오류가 발생했습니다(컨트롤러 이름은 RestController).
됐어요!!!저는 믿고 싶지 않았지만, 문제는 Global.asax 라우팅 순서와 관련이 있습니다.
다음과 같이 작동하지 않는 경우:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 4th
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
다음과 같이 작동합니다.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 2nd
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
미친 거 알아요
기존 MVC(5) 프로젝트 내에서 WebAPI를 사용하려면 다음 단계를 수행해야 합니다.
1. WebApi 패키지 추가:
Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.WebHost
Newtonsoft.Json
2.추가WebApiConfig.cs로 철하다.App_Start폴더:
using System.Web.Http;
namespace WebApiTest
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
3.다음 행을 추가합니다.Glabal.asax:
GlobalConfiguration.Configure(WebApiConfig.Register);
중요한 참고: 정확하게 다음에 위 줄을 추가해야 합니다.AreaRegistration.RegisterAllAreas();
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//\\
GlobalConfiguration.Configure(WebApiConfig.Register);
//\\
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
"새로운 경로를 추가할 때는 상단에 특정 경로를 추가한 후 최종적으로 더 일반적인 경로를 추가해야 합니다.그렇지 않으면 웹 앱이 제대로 라우팅되지 않습니다."
위의 내용은 다음과 같습니다. http://www.codeproject.com/Tips/771809/Understanding-the-Routing-Framework-in-ASP-NET-MVC
답변이 이미 제공된 것은 알지만, 이를 통해 Global Configuration을 입력해야 하는 이유를 이해할 수 있습니다.구성(WebApiConfig).등록); RouteConfig 이전.경로 등록(RouteTable).경로);
언급URL : https://stackoverflow.com/questions/22401403/404-error-after-adding-web-api-to-an-existing-mvc-web-application
'codememo' 카테고리의 다른 글
| 암호에 따라 문자열을 인코딩하는 간단한 방법? (0) | 2023.06.27 |
|---|---|
| 스프링 데이터 - Mongodb - 내포된 객체에 대한 방법으로 찾기 (0) | 2023.06.22 |
| 최대 연결 풀 크기 (0) | 2023.06.22 |
| Windows 경로를 Python 문자열 리터럴로 작성하는 방법은 무엇입니까? (0) | 2023.06.22 |
| DBMS_JOB 대 DBMS_Scheduler (0) | 2023.06.22 |