我正在使用Web API(asp net 5)中的REST服务,网站可以成功向其发送请求,但是当服务将请求选项发送到网站时,回复显示{{1 }}
Fiddler Screenshot of the "Options" request
服务的控制器由
配置HTTP 1/1 404 Not Found
<小时/> 网站必须访问的功能是:
public class Startup {
public void ConfigureServices (IServiceCollection services) {
services.AddCors();
services.AddMvc();
}
}
访问此功能的网站(发送路由到类调用索引)是使用ajax
实现的[Route("/operator")] // localhost:5000/operator
public class OperatorController : Controller
[EnableCors(origins:'*', headers>'*', methods:'*');
public IActionResult Index()
{
return new HttpOkObject("Hello, select your operation");
}
<小时/> [编辑] 添加
行
<script type="text/javascript">
$(document).ready(function() {
var options = {};
options.url = "http://localhost:5000/installments";
options.type = "GET";
options.contentType = "application/jsonp";
// options.dataType="jsonp";
options.success = function (results) {
alert(results.join);
};
options.error = function(evt){
alert(evt.status + " - " + evt.statusText)
};
$.ajax(options);
});
</script>
在
<pre><code>app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Allow-Origin", "*"); await next(); });</code></pre>
添加所需的标题,但是我收到错误
app.UseMvc();
答案 0 :(得分:0)
您必须指定要用于控制器内部功能的路径和方法。您可以在Startup类中定义默认映射。
HttpConfiguration configuration = new HttpConfiguration();
configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
或者您可以使用以下标记在函数中显式声明路径。
[EnableCors(origins:'*', headers>'*', methods:'*');
[HttpGet]
[Route("printheads/")]
public IActionResilt Index()
{
return new HttpOkObject("Hello, select your operation");
}
答案 1 :(得分:0)
通过执行以下操作解决了这个问题:
在中的Setup.cs中
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
添加以下行:
app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Allow-Origin", "*"); await next(); });
app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Allow-Methods", "*"); await next(); });
app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Max-Age", "3600"); await next(); });
app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Allow-Headers", "*"); await next(); });