친구, VS2013을 사용 중이고 응용 프로그램에서 라우팅 관련 문제가 있습니다. 나는 내 문제를 설명하기 위해 매우 간단한 웹 애플리케이션을 생성하고 그것을 여기 GitHub의에 게시 한 :Fluent-Nhibernate + Web Api v2 + Unity
https://github.com/ewhitmore/RoutingIssues/
은 현재 내가 GET 하나의 컨트롤러가 내가 그것을 사용하려고하면, PUT, POST와 동사를 삭제하지만, , GET 및 POST는 작동하지만 DELETE 및 PUT은 수행하지 않습니다.
다음 오류가 발생합니다. "405 Method Not Allowed"및 "message": "요청한 리소스가 http 메서드 'PUT'을 지원하지 않습니다."
컨트롤러에 중단 점을 넣었으므로 PUT/DELETE 조작으로 컨트롤러에 연결되지 않습니다.
저는 AngularJS ng-resources, Postman 및 REST Console을 동일한 결과로 사용했습니다.
내 컴퓨터에서 webdev를 제거하고 여러 가지 라우팅 기법을 시도했지만 아무런 효과가 없었습니다. 이것은 모든 로컬이며 그래서 내가 말할 수있는 한 크로스 사이트/서버/도메인 (CORS) 문제는 아닙니다. 이 시점에서 나는이 문제에 대해 20 시간이 넘는 일을하고 있으며 포기할 것입니다. 어떤 도움 이라든지 대단히 감사 할 것입니다.
코드는 아래의 강조 :
UserProfileContoller :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.Practices.Unity;
using TrackInstant.Models.Entities;
using TrackInstant.Services;
namespace TrackInstant.Controllers
{
[AllowAnonymous]
[RoutePrefix("api/userprofile")]
public class UserProfileController : ApiController
{
[Dependency]
public UserProfileService UserProfileService { private get; set; }
[HttpGet]
public IEnumerable<UserProfile> GetAllUsers()
{
return UserProfileService.GetAllUserProfiles();
}
[HttpGet]
[ResponseType(typeof(UserProfile))]
public UserProfile GetUserById(int id)
{
UserProfile userProfile = UserProfileService.GetUser(id);
if (userProfile == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return userProfile;
}
[HttpPost]
[ResponseType(typeof(UserProfile))]
public IHttpActionResult PostUser(UserProfile userProfile)
{
if (userProfile == null)
{
return BadRequest();
}
UserProfileService.Save(userProfile);
return CreatedAtRoute("DefaultApi", new { id = userProfile.UserId }, userProfile);
}
[HttpPut]
public IHttpActionResult PutUser(int id, UserProfile userProfile)
{
UserProfile persistentUser = UserProfileService.GetUser(id);
if (persistentUser == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
persistentUser.Email = userProfile.Email;
UserProfileService.UpdateUser(persistentUser);
return StatusCode(HttpStatusCode.NoContent);
}
[HttpDelete]
[ResponseType(typeof(UserProfile))]
public IHttpActionResult DeleteUser(int id)
{
UserProfile userProfile = UserProfileService.GetUser(id);
if (userProfile == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
UserProfileService.DeleteUser(userProfile);
return Ok(userProfile);
}
}
}
의 Web.config 하이라이트 :
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="FormsAuthenticationModule" />
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Global.asax에
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Http;
using TrackInstant.App_Start;
namespace TrackInstant
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
WebApiFilterConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
HibernateConfig.InitHibernate();
UnityBootstrapper.Initialise();
}
public override void Dispose()
{
HibernateConfig.SessionFactory.Dispose();
base.Dispose();
}
}
}
RouteConfig
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace TrackInstant
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings {AutoRedirectMode = RedirectMode.Permanent};
routes.EnableFriendlyUrls(settings);
}
}
}
WebApiConfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace TrackInstant
{
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 }
);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
}
}
WebApiFilterConfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;
namespace TrackInstant.App_Start
{
public class WebApiFilterConfig
{
public static void RegisterGlobalFilters(HttpFilterCollection filters)
{
filters.Add(new HibernateSessionFilter());
}
}
}
이것은 풋의 우편 배달부의 출력 :
이 내 작업 컨트롤러 모습입니다. "Allow"에 주목하십시오 :'Allow → GET, POST Cache-Control → no-cache Content-Length → 79 Content-Type → application/json; 문자셋 = UTF-8 날짜 → 2013년 (화) 12월 17일 그리니치 표준시 16시 09분 28초 는 마이크로 소프트 IIS/8.0 X-ASPNET-버전 → 4.0.30319 X → → -1 에서 Pragma → 노 캐시 서버 만료 -Powered-으로 → ASP.NET X-있는 SourceFiles → =? UTF-8? B? QzpcVXNlcnNcd2hpdG0xZWtcRG9jdW1lbnRzXFZpc3VhbCBTdHVkaW8gMjAxM1xQcm9qZWN0c1xSb3V0aW5nXFJvdXRpbmdJc3N1ZXNcVHJhY2tJbnN0YW50XGFwaVx1c2VycHJvZmlsZQ ==? = ' – Eric
내가 WebDAV를 설치 한 경우이 문제가 발생할 수 있다고 생각합니다. – Andy
게시하기 전에 내 컴퓨터에서 WebDAV를 완전히 제거했습니다. 아직도 운이 없다. – Eric