这不是一个问题 - 在此发布以供参考:
使用WebService时,出现以下错误:
对于意外以/ myMethodName结尾的URL,无法识别请求格式
我尝试按照http://enable-cors.org/server_aspnet.html中的步骤 使我的RESTful API(使用ASP.NET WebAPI2实现)与跨源请求(CORS Enabled)一起工作.除非我修改web.config,否则它无法正常工作.
我安装了WebApi Cors依赖:
install-package Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api
Run Code Online (Sandbox Code Playgroud)
然后在我App_Start的课程中我得到WebApiConfig如下:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
var constraintsResolver = new DefaultInlineConstraintResolver();
constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint));
config.MapHttpAttributeRoutes(constraintsResolver);
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
//config.EnableSystemDiagnosticsTracing();
config.Services.Replace(typeof(ITraceWriter), new SimpleTraceWriter(WebContainerManager.Get<ILogManager>()));
config.Services.Add(typeof(IExceptionLogger), new SimpleExceptionLogger(WebContainerManager.Get<ILogManager>()));
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
}
}
Run Code Online (Sandbox Code Playgroud)
但之后我运行应用程序,我请求Fiddler的资源,如: http:// localhost:51589/api/v1/persons ,在响应中,我看不到我应该看到的HTTP头,例如:
Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONSAccess-Control-Allow-Origin: *我错过了一步吗?我在控制器上尝试了以下注释:
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
相同的结果,没有启用CORS. …
我创建了一个web api 2,我正在尝试对它进行跨域请求,但是我收到以下错误:
选项http://www.example.com/api/save 405(方法不允许)
我已经浏览了一下这个问题的大多数解决方案是说我需要从NuGet安装COR并启用它所以我已经安装了包并标记了我的控制器
[EnableCors("*", "*", "*")]
Run Code Online (Sandbox Code Playgroud)
但这仍然没有解决问题.
我ApiController只有以下Save方法:
[ResponseType(typeof(int))]
public IHttpActionResult Save(Student student)
{
if (ModelState.IsValid)
{
using (StudentHelper helper = new StudentHelper())
{
return Ok(helper.SaveStudent(student));
}
}
else
{
return BadRequest(ModelState);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我来自不同领域的js:
$.ajax({
type: "POST",
crossDomain: true,
data: JSON.stringify(student),
crossDomain: true,
url: 'http://www.example.com/api/save',
contentType: "application/json",
success: function (result) {
console.log(result);
}
});
Run Code Online (Sandbox Code Playgroud)
我还需要做些什么来实现这个目标吗?
我从angular.js客户端向asp.net web api PUT方法发出以下请求:
var org = {
OrgId: 111,
name: 'testing testing'
};
$http.put("http://localhost:54822/api/data/putorganisation/1/", org).then(function(status) {
console.log("success PUT");
return status.data;
});
Run Code Online (Sandbox Code Playgroud)
但是获得以下errormsg(在fiddler中):
{"message":"The requested resource does not support http method 'OPTIONS'."}
Run Code Online (Sandbox Code Playgroud)
这是我的asp.net web api web.config文件的一部分:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type,x-xsrf-token,X-Requested-With" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<remove name="WebDAV" /> …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Prototype/AJAX访问Web服务并遇到一个我无法弄清楚的错误:似乎当我向服务器发出请求时,我的请求被解释为OPTIONS而不是GET请求(反过来抛出一个501 - 未实现的错误,因为服务器只根据我的理解允许GET请求Access-Control-Request-Method:).我在AJAX /请求公式中遗漏了可能导致此错误的内容吗?我在这里阅读了一些CORS/preflighted请求,但我不确定当我的代码看起来合规时它是如何应用的...
这是相关的AJAX请求:
function fetchMetar() {
var station_id = $("station_input").value;
new Ajax.Request(REQUEST_ADDRESS, {
method: "get",
parameters: {stationString: station_id},
onSuccess: displayMetar,
onFailure: function() {
$("errors").update("an error occurred");
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我从Chrome获得的错误和相关请求信息:
Request URL:http://weather.aero/dataserver_current/httpparam?
dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=3
&mostRecent=true&stationString=&stationString=KSBA
Request Method:OPTIONS
Status Code:501 Not Implemented
Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, x-prototype-version, x-requested-with, accept
Access-Control-Request-Method:GET
Connection:keep-alive
Host:weather.aero
Origin:http://domain.com
Referer:http://domain.com/.../...html
Run Code Online (Sandbox Code Playgroud)
我能在这里俯瞰什么?为什么Chrome会将请求作为OPTIONS而不是GET发送?当Chrome吐出Access-Control-Request-Headers:信息时,这些信息是否仅是请求中允许的唯一标头?
谢谢!
我们有以下设置:
Front end code : REACT (Hosted using express js) (lets call this www.domainA.com)
Backend : .NET WEB API (Hosted in IIS 7.5) (lets call this www.domainB.com)
Run Code Online (Sandbox Code Playgroud)
FE应用程序的域正在向Web api发出GET数据和POST数据的请求.
GET工作正常,但每当我尝试将数据发布到Web API时,它都会抛出以下错误:
Request URL: http://www.domainB.com/api/postdataoperation
Request Method: OPTIONS
Status Code: 403 Forbidden
Run Code Online (Sandbox Code Playgroud)
我查看了许多CORS文章并继续在IIS中设置HTTPResponseHeaders,如下所示:
Access-Control-Allow-Methods : POST,GET,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin : http://www.domainA.com
Run Code Online (Sandbox Code Playgroud)
反应解决方案的发布请求如下:
axios.post(`http://www.domainB.com/api/postdataoperation`, {userId});
Run Code Online (Sandbox Code Playgroud) 我有一个带有令牌身份验证的ASP.NET Web Api 2.0项目,所有工作主要完成本文之后:
使用ASP.NET Web API 2,Owin和Identity,Bit Of Technology进行基于令牌的身份验证
但是我很难理解我的Startup.cs中的这行代码究竟是做什么的:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Run Code Online (Sandbox Code Playgroud)
这不会使Web Api将Access-Control-Allow-Origin标头添加到我的API响应中,换句话说,它不会在我的Web Api中启用Cors(仍然试图了解如何执行此操作).它甚至没有将它添加到我的承载令牌认证服务器响应中.我必须将此代码提供给OAuthAuthorizationServerProvider:
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
Run Code Online (Sandbox Code Playgroud)
在我的令牌提供者端点响应上启用Cors.
那么这个Microsoft.Owin.Cors中间件的用途是什么呢?因为我到处读到有关Web Api 2.0和Cors的这一行代码
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Run Code Online (Sandbox Code Playgroud)
过来:
我在使用AngularJS的服务器上启用CORS时遇到问题.我正在使用Angular 1.2.16,这是我的服务器配置:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name, Authorization"
Header set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"
Run Code Online (Sandbox Code Playgroud)
我可以使用以下请求:
$http.post(configuration.authUrl, {username: 'username', password: 'password'})
.success(function (data) {
$cookieStore.put(configuration.sessionName, {
token: data.authenticationToken,
user: data.user
});
})
.error(function () {}));
Run Code Online (Sandbox Code Playgroud)
因为此请求不使用自定义标头.
当我之后尝试请求以下内容时:
Balance.get()余额为:
angular.module('portalApp')
.factory('Balance', ['$resource', 'Auth', 'configuration', function ($resource, Auth, configuration) {
return $resource(configuration.balanceUrl, {}, {
get: {
method: 'GET',
isArray: false,
headers: {
Authorization: Auth.getAuthToken() …Run Code Online (Sandbox Code Playgroud) 邮递员一切都很好。我在服务器上发布了Bearer令牌,并获得了预期的结果。
Angular 2请求:
//app component
test(){
return this.httpService.get('api/user/get', 'application/json')
.subscribe(data=>{
console.log({'loggedIn': true, 'messageText': 'test succeeded'});
},
error=>{
console.log({'loggedIn': false, 'messageText': error});
}
);
}
//http-service
get(url:string, contentType:string):Observable<any> {
let baseUrl:string = "http://localhost:1382/";
let headers = new Headers({
'Accept': 'application/json'
});
//append content-type to headers
headers.append('Content-type', contentType);
//check if localStorage contains token. If yes, append authorization to headers
let token = localStorage.getItem('access_token');
if (token !== '[object Object]' && token !== null) {
headers.append('Authorization', 'Bearer' + ' ' + token);
} …Run Code Online (Sandbox Code Playgroud) 我创建了一个WEB API使用ASP.NET MVC WEB API 2.0.Web API包含像login,register等等方法.
我AngularJS用来调用WEB API方法,但它调用了两次.例如,当我调用POST方法时,它首先调用OPTION(我没有创建任何OPTION方法),然后调用POST方法.
我的代码:(用于登录)
HTML:
<div class="container" ng-controller="UserAccount">
<form ng-submit="loginNow(user)">
<input type="email" placeholder="Enter Email" required ng-model="user.email" id="txtEmail" class="form-control" />
<br />
<input type="password" placeholder="Enter Password" required ng-model="user.password" id="txtPwd" class="form-control" />
<br />
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)
AngularJS控制器:
$scope.loginNow = function (user) {
$http.post(rootURL + "login", { email: user.email, password: user.password })
.success(function …Run Code Online (Sandbox Code Playgroud) cors ×5
angularjs ×3
c# ×3
asp.net-mvc ×2
javascript ×2
rest ×2
ajax ×1
angular ×1
asp.net ×1
axios ×1
express ×1
http-headers ×1
node.js ×1
owin ×1
post ×1
prototypejs ×1
web-services ×1