오류 : 요청 헤더 필드 Content-Type은 Access-Control-Allow-Headers에서 허용되지 않습니다.
vS2012를 사용하여 mvc4 웹 API 프로젝트를 만들었습니다. 다음 자습서를 사용하여 Cross-Origin 리소스 공유를 해결했습니다. "http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api- rc-version.aspx "입니다. 성공적으로 작동하고 있으며 클라이언트 측에서 서버로 데이터를 성공적으로 게시합니다.
그 후 프로젝트에서 Autherization을 구현하기 위해 다음 자습서를 사용하여 OAuth2를 구현했습니다. "http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for -mvc-two-legged-implementation.aspx ". 이것은 클라이언트 측에서 RequestToken을 얻는 데 도움이됩니다.
그러나 클라이언트 측에서 데이터를 게시 할 때 "XMLHttpRequest가 http : //를로드 할 수 없습니다. 요청 헤더 필드 Content-Type이 Access-Control-Allow-Headers에서 허용되지 않습니다."라는 오류가 발생했습니다.
내 클라이언트 측 코드는 다음과 같습니다.
function PostLogin() {
var Emp = {};
Emp.UserName = $("#txtUserName").val();
var pass = $("#txtPassword").val();
var hash = $.sha1(RequestToken + pass);
$('#txtPassword').val(hash);
Emp.Password= hash;
Emp.RequestToken=RequestToken;
var createurl = "http://localhost:54/api/Login";
$.ajax({
type: "POST",
url: createurl,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Emp),
statusCode: {
200: function () {
$("#txtmsg").val("done");
toastr.success('Success.', '');
}
},
error:
function (res) {
toastr.error('Error.', 'sorry either your username of password was incorrect.');
}
});
};
내 API 컨트롤러는 다음과 같습니다.
[AllowAnonymous]
[HttpPost]
public LoginModelOAuth PostLogin([FromBody]LoginModelOAuth model)
{
var accessResponse = OAuthServiceBase.Instance.AccessToken(model.RequestToken, "User", model.Username, model.Password, model.RememberMe);
if (!accessResponse.Success)
{
OAuthServiceBase.Instance.UnauthorizeToken(model.RequestToken);
var requestResponse = OAuthServiceBase.Instance.RequestToken();
model.ErrorMessage = "Invalid Credentials";
return model;
}
else
{
// to do return accessResponse
return model;
}
}
내 webconfig 파일은 다음과 같습니다.
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oauth" type="MillionNodes.Configuration.OAuthSection, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<oauth defaultProvider="DemoProvider" defaultService="DemoService">
<providers>
<add name="DemoProvider" type="MillionNodes.OAuth.DemoProvider, MillionNodes" />
</providers>
<services>
<add name="DemoService" type="MillionNodes.OAuth.DemoService, MillionNodes" />
</services>
</oauth>
<system.web>
<httpModules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
</httpModules>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral" preCondition="" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
<dotNetOpenAuth>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
이 게시물에서 알 수 있듯이 Chrome의 오류 : Access-Control-Allow-Headers에서 Content-Type을 허용하지 않습니다. web.config에 추가 헤더를 추가하십시오.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin
to *
, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
Make sure that you haven't already used header
in another file, or you will get a nasty error. See the docs for more.
I know it's an old thread I worked with above answer and had to add:
header('Access-Control-Allow-Methods: GET, POST, PUT');
So my header looks like:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
And the problem was fixed.
For Nginx, the only thing that worked for me was adding this header:
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
Along with the Access-Control-Allow-Origin header:
add_header 'Access-Control-Allow-Origin' '*';
Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.
'program story' 카테고리의 다른 글
UIView와 CALayer의 차이점은 무엇입니까? (0) | 2020.08.21 |
---|---|
CSS : img : hover에서 이미지 src 변경 (0) | 2020.08.21 |
정규식은 물음표 뒤의 모든 항목과 일치합니까? (0) | 2020.08.21 |
LESS CSS 중첩 클래스 (0) | 2020.08.21 |
레일 3에서 CSRF 토큰 끄기 (0) | 2020.08.21 |