기존 ASP.NET MVC (5) 웹 응용 프로그램 프로젝트에 웹 API를 추가하는 방법은 무엇입니까?
새 MVC (5) 프로젝트를 만들 때 웹 API 확인란을 선택 (프로젝트에 추가)하지 않은 경우 웹 API를 추가하고 작동 시키려면 어떻게해야합니까?
많은 마이그레이션 질문이 있지만 MVC 5 프로젝트에 웹 API를 추가하기위한 완전한 최신 단계가없는 것으로 보이며 이전 답변 중 일부에서 변경된 것으로 보입니다.
GlobalConfiguration.Configure (WebApiConfig.Register) MVC 4 추가
MVC 프로젝트 업데이트
Nuget 을 사용 하여 최신 웹 API를 얻으십시오.
프로젝트-마우스 오른쪽 버튼으로 클릭-Nuget 패키지 관리-웹 API (Microsoft ASP.NET 웹 API ...)를 검색하여 MVC 프로젝트에 설치하십시오.
그런 다음 여전히 웹 API 라우팅 이 작동해야합니다. Microsoft의 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.HelpPage를 설치합니다. 기능에 대해서는 http://channel9.msdn.com/Events/Build/2014/3-644(~42 분)를 참조 하십시오 . 매우 도움이됩니다!
Nuget Console : 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";
}
//...
}
Now you can test in IE/FF/Chrome as usual, or in the JavaScript consoles for non-get testing.
(With just the controller in the URL it will call the GET() action in the new Web API Controller, it's automatically mapped to methods/actions depending on the REST e.g. PUT/POST/GET/DELETE. You don't need to call them by action like in MVC) The URL directly:
http://localhost:PORT/api/CONTROLLERNAME/
Alternatively use jQuery to query the controller. Run the project, Open the console (F12 in IE) and try run an Ajax query. (Check your PORT & CONTROLLERNAME)
$.get( "http://localhost:PORT/api/CONTROLLERNAME/", function( data ) {
//$( ".result" ).html( data );
alert( "Get data received:" + data);
});
Side note: There are some pros/cons to consider when combining MVC and Web API in a project
WebAPI Help verification: http://localhost:PORT/help
'Programming' 카테고리의 다른 글
데스크톱 환경에서 가상 컴퓨터를 실행하기 위해 vagrant 사용 (0) | 2020.06.19 |
---|---|
리스트의리스트를 초기화하는 파이썬 (0) | 2020.06.19 |
무중단 프로세스 란 무엇입니까? (0) | 2020.06.19 |
오프라인에서 OKHttp로 Retrofit을 사용하여 캐시 데이터를 사용할 수 있음 (0) | 2020.06.18 |
FlexBox에서 div 채우기를 * 수평 * 공간으로 유지 (0) | 2020.06.18 |