![](/img/trans.png)
[英]How to Run C# ASP.NET Core 2.1 and Node.js with Different Ports in Nginx?
[英]Run AngularUI and Asp.net WebApi on different ports
我在不同的端口中有2个单独的项目,一个是asp.net Web api,另一个是angularjsUI,它消耗了webapi服务。 当我从我的角度项目中调用webapi服务时,该服务未命中。
如果service和angularUi都在同一个项目中,那么没有问题,我可以使用该服务。
使用的技术:Vs2015,Angularjs1.6,WebApi2
如何在不同端口的这两个单独的项目之间成功进行通信。 范例:
步骤1:这些文件在我的angularUI项目中
LoginController.js
$scope.RegisterClick=function(myregister) {
var apiRoute = "http://localhost:51002/api/LoginApi";
var registerdata = LoginService.post(apiRoute, registeruserdetails);
}
LoginService.js
myqcapp.service("LoginService", function ($http) {
this.post = function (apiRoute, Model) {
var loginresult = $http({
method: "post",
url: apiRoute,
dataType: 'json',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
data: Model
});
return loginresult;
}
});
步骤2:在我的WebApi项目中
LoginApiController.cs
public class LoginApiController : ApiController
{
[ResponseType(typeof(Register))]
public IHttpActionResult Post(Register registercls)
{
if (ModelState.IsValid)
{
registerbs.Add(registercls);
return CreatedAtRoute("DefaultApi", new { id = registercls.Userid }, registercls);
}
else
{
return BadRequest(ModelState);
}
}
}
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{Controller}/{id}",
defaults: new {
Controller="LoginApi",
id = RouteParameter.Optional
}
);
}
您需要在提供Web API的Project / Web应用程序上启用跨站点脚本。
您的UI / API使用者位于单独的项目/端口中,并且如果禁用了跨站点脚本(CORS),API服务器将不会将该请求视为“ 同一原始请求 ”。
您需要在App_Start文件夹中WebApiConfig类的Register(HttpConfiguration conf)
方法内调用EnableCors()
。 如果默认情况下不存在WebApiConfig,则可能必须添加它。
接下来,您需要使用[EnableCors]批注装饰控制器,说我的网页位于localhost:8080,只需将其装饰为:
[EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
public class LoginApiController : ApiController
{
.....
}
您还可以允许任何站点使用*通配符访问您的API
[EnableCors(origins: "*", headers: "*", methods: "*")]
您需要了解有关CORS的更多信息。 您还需要解决CORS的安全性问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.