programing

기존 ASP에 웹 API를 추가하는 방법.NET MVC (5) 웹 애플리케이션 프로젝트?

lastcode 2023. 4. 27. 22:27
반응형

기존 ASP에 웹 API를 추가하는 방법.NET MVC (5) 웹 애플리케이션 프로젝트?

새 MVC(5) 프로젝트를 만들 때 웹 API 확인란을 선택(프로젝트에 추가)하지 않았다고 가정하면 웹 API를 추가하고 작동하려면 무엇이 필요합니까?

마이그레이션 질문이 많지만 MVC 5 프로젝트에 웹 API를 추가하기 위한 완벽하고 최신 단계는 없는 것으로 보이며 기존 답변 중 일부와 달라진 것으로 보입니다.

MVC 4에 웹 API 추가

글로벌 구성을 추가하는 중입니다.구성(WebApiConfig).등록) MVC 4

MVC 프로젝트 업데이트

Nuget을 사용하여 최신 웹 API를 얻습니다.

프로젝트 - 마우스 오른쪽 단추 클릭 - Nuget 패키지 관리 - 웹 API(Microsoft ASP) 검색NET Web API...)를 MVC 프로젝트에 설치합니다.

그러면 웹 API 라우팅이 작동하도록 해야 합니다.마이크로소프트의 ASP 구성에서.NET 웹 API 2

App_Start/ 폴더에 WebApiConfig.cs 추가

using System.Web.Http;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // TODO: Add any additional configuration code.

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        // WebAPI when dealing with JSON & JavaScript!
        // Setup json serialization to serialize classes to camel (std. Json format)
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
        }
    }
}

MVC 프로젝트가 있는 경우 Global.asax.cs 가 있고 새 경로를 추가합니다.Global.asax.cs 경로의 순서는 매우 중요합니다.다음을 사용하는 오래된 예가 있습니다.WebApiConfig.Register

다음 행을 Global.asax.cs 에 추가합니다. GlobalConfiguration.Configure(WebApiConfig.Register);

protected void Application_Start()
{
    // Default stuff
    AreaRegistration.RegisterAllAreas();

    // Manually installed WebAPI 2.2 after making an MVC project.
    GlobalConfiguration.Configure(WebApiConfig.Register); // NEW way
    //WebApiConfig.Register(GlobalConfiguration.Configuration); // DEPRECATED

    // Default stuff
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

WebAPI 도움말

매우 유용한 WebAPI 도움말 페이지를 보려면 WebAPI를 설치합니다.도움말 페이지.기능에 대해서는 http://channel9.msdn.com/Events/Build/2014/3-644 (~42분 후)를 참조하십시오.그것은 매우 도움이 될 것 같습니다!

너겟 콘솔:Install-Package Microsoft.AspNet.WebApi.HelpPage

WebAPI가 작동하는지 확인하는 방법

컨트롤러 폴더에 -> 새 항목 추가 -> 웹 API 컨트롤러 클래스.

public class TestController : ApiController
{
    //public TestController() { }

    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }
    //...
}

이제 IE/FF/Chrome에서 평소처럼 테스트하거나 JavaScript 콘솔에서 테스트하지 않고 테스트할 수 있습니다.

(URL에 컨트롤러만 있으면 새 Web API Controller에서 GET() 액션을 호출하며, REST에 따라 메서드/액션(예: PUT/POST/GET/DELETE)에 자동으로 매핑됩니다.MVC와 같이 직접 전화를 걸 필요는 없습니다) URL:

http://localhost:PORT/api/CONTROLLERNAME/

또는 jQuery를 사용하여 컨트롤러를 쿼리합니다.프로젝트를 실행하고 콘솔을 열고(IE의 F12) Ajax 쿼리를 실행해 보십시오. (포트 및 컨트롤러 이름 확인)

$.get( "http://localhost:PORT/api/CONTROLLERNAME/", function( data ) {
    //$( ".result" ).html( data );
    alert( "Get data received:" + data);
});

참고 사항:프로젝트에서 MVC와 Web API를 결합할 때 고려해야 할 몇 가지 장단점이 있습니다.

WebAPI 도움말 확인: http://localhost:PORT/help

언급URL : https://stackoverflow.com/questions/26067296/how-to-add-web-api-to-an-existing-asp-net-mvc-5-web-application-project

반응형