如果您想了解angularJs–405方法不允许在WebAPI2(OWIN)和angularjs表达式中不能使用的运算符的知识,那么本篇文章将是您的不二之选。我们将深入剖析angularJs–405方
如果您想了解angularJs – 405方法不允许在WebAPI2(OWIN)和angularjs表达式中不能使用的运算符的知识,那么本篇文章将是您的不二之选。我们将深入剖析angularJs – 405方法不允许在WebAPI2(OWIN)的各个方面,并为您解答angularjs表达式中不能使用的运算符的疑在这篇文章中,我们将为您介绍angularJs – 405方法不允许在WebAPI2(OWIN)的相关知识,同时也会详细的解释angularjs表达式中不能使用的运算符的运用方法,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- angularJs – 405方法不允许在WebAPI2(OWIN)(angularjs表达式中不能使用的运算符)
- angularjs – Angular 1.2不再允许在同一个元素上使用多个隔离的范围指令?
- angularjs – Angular JS MVC Web API模型/参数不绑定.NET Core
- angularjs – Angular POST to Web API不传递数据
- angularjs – Angular – > Web Api 2:“没有’Access-Control-Allow-Origin’标题”
angularJs – 405方法不允许在WebAPI2(OWIN)(angularjs表达式中不能使用的运算符)
webAPI和Angular位于不同的站点上。
在Startup.cs我有:
public void Configuration(IAppBuilder app) { ConfigureOAuth(app); var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.UseWebApi(config); } private void ConfigureOAuth(IAppBuilder app) { var oAuthServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true,TokenEndpointPath = new PathString(Paths.TokenPath),AccesstokenExpireTimeSpan = TimeSpan.FromMinutes(30),Provider = Kernel.Get<IOAuthAuthorizationServerProvider>() }; app.USEOAuthAuthorizationServer(oAuthServerOptions); OAuthBearerOptions = new OAuthBearerAuthenticationoptions(); app.USEOAuthBearerAuthentication(OAuthBearerOptions); }
然后在控制器上,我的方法设置为允许匿名:
[AllowAnonymous] public bool PostRegister(UserSignupForm form) { ... }
我也更新了web.config:
<system.webServer> <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" /> </handlers> </system.webServer>
在角度方面,我做了一个简单的$ http.post调用:
saveRegistration: function (registration) { return $http.post(baseUrl + '/api/signup/register',registration).then(function (response) { return response; }); }
当使用Postman进行调用时,我得到了一个成功的响应,但是当从Angular进行相同的调用时,我得到了405错误。
BitOfTech示例站点正在发送相同的请求标头,但能够获取Access-Control-Allow-XXX标头
我已经更新了我的代码以跟随Token Based Authentication using ASP.NET Web API 2,Owin,and Identity
[AllowAnonymous] [Route("Register")] [AcceptVerbs("OPTIONS")] public async Task<IHttpActionResult> Register() { return Ok(); }
angularjs – Angular 1.2不再允许在同一个元素上使用多个隔离的范围指令?
这在1.0中工作,但是Angular 1.2现在在尝试执行此操作时会生成错误
Multiple directives asking for new/isolated scope
基于项目git历史出现Angular 1.2更改行为,以保持两个隔离的指令在同一元素上分开.这是一件好事,当在同一元素上放置两个“Attribute”指令时,它可以正常工作.
即
<div my:directive="myDirectiveData" my:other-directive="myOtherDirectiveData" />
像你期望的那样工作.
然而
<my:directive my:directive-data="myDirectiveData" my:other-directive="myOtherDirectiveData" />
引发上述错误. (多个指令要求新/隔离范围)
在这种情况下,我希望每个指令仍然与它们自己的非共享隔离范围并行存在.
这在Angular 1.2中仍然可行吗?
Scenario directive #1 directive #2 Result 1 no new scope no new scope Both directives use the controller's scope. (This should be obvIoUs.) 2 new scope new scope Both directives share one new child scope. 3 new scope no new scope Both directives share one new child scope. Why does dir #2 use the child scope? This seems odd to me. 4 isolate scope no new scope Angular v1.0: both directives share the isolate scope. Angular v1.2+: dir #1 uses the isolate scope,dir #2 uses the controller's scope.
请注意,不允许以下方案(Angular引发错误):
Scenario directive #1 directive #2 5 isolate scope new scope 6 isolate scope isolate scope
angularjs – Angular JS MVC Web API模型/参数不绑定.NET Core
我有一个apiService来处理对服务器的所有POST和GET请求,如下所示:
module TBApp { export class apiService { static $inject = ['$http','notificationService']; constructor(private $http,private notificationService: notificationService) { } get(url,config,success,failure) { return this.$http.get(url,config) .then(result => { this.handleResponse(result,success); },result => { this.handleError(result,failure) }); } post(url,data,failure) { return this.$http.post(url,data) .then(result => { this.handleResponse(result,failure) }); } handleResponse(result,success) { alert('success'); success(result); } handleError(result,failure) { if (result.status === '401') { this.notificationService.displayError('Authentication required.'); //this.$rootScope.prevIoUsstate = this.$location.path(); //this.$location.path('/login'); } else if (failure !== null) { failure(result); } } } }
现在,当我发送此请求时:
onCompanyChanged(selectedCompany,model,companyName) { this.apiService.post('/api/Dashboard/GetAssetListByCompany',{ companyId: selectedCompany.id },response => { this.assetListviewmodel = response.data.data; },response => { this.notificationService.displayError(response.data.message); }); }
它没有绑定控制器中的companyId
这是控制器:
[Route("api/[controller]")] public class DashboardController : BaseController { [HttpPost] [Route("GetAssetListByCompany")] public IActionResult GetAssetListByCompany([FromBody]int companyId) { return CreateJsonResult(() => { if (companyId == 0) { return new xPTJsonResult(null,xPTStatusCodesEnum.Success,"Company Id is 0"); } //var treeModel = _dashboardProvider.GetTreeModelByCompany(companyId,usermodel); return new xPTJsonResult(null,"Loaded assets successfully"); }); } }
即使我在浏览器中检查了请求,也表明companyId在Payload中.
NOTE: The same function works when I post a viewmodel
编辑
在上面的场景中,我只将一个参数传递给控制器,但在某些情况下,我希望能够在不使用viewmodel的情况下传递2或3个参数.
例如
public IActionResult GetAssetListByCompany([FromBody]int companyId,[FromBody]int assetId) {....
要么
public IActionResult GetAssetListByCompany([FromBody]int companyId,[FromBody]int assetId,[FromBody]bool canEdit = false) {.....
然后在客户端我可以这样做:
this.apiService.post('/api/Dashboard/GetAssetListByCompany',{ companyId: selectedCompany.id,assetId: 123 }.....
要么
this.apiService.post('/api/Dashboard/GetAssetListByCompany',canEdit: true,assetId: 22 }....
解决方法
MVC改变了
有关各种选项,请参阅Model Binding,此处的最佳方法是基于查询字符串进行绑定,因为您只需要一个基本类型.如果您有一个基本类型数组仍然可以绑定到查询字符串,则查询字符串变量名称将为每个值重复一次.
因此,我们所做的唯一更改是指定参数来自查询字符串,并且它与Http Get请求而不是Post相关联.
[Route("api/[controller]")] public class DashboardController : BaseController { [HttpGet] // change to HttpGet [Route("GetAssetListByCompany")] public IActionResult GetAssetListByCompany([FromQuery]int companyId) // use FromQuery { return CreateJsonResult(() => { if (companyId == 0) { return new xPTJsonResult(null,"Company Id is 0"); } //var treeModel = _dashboardProvider.GetTreeModelByCompany(companyId,usermodel); return new xPTJsonResult(null,"Loaded assets successfully"); }); } }
AngularJS发生了变化
我们扩展apiService以允许使用HttpGet传递调用数据.这可以使用params on the $http call完成,它将使用名称作为查询字符串值名称和值作为值部分,根据传入的数据动态创建URL.
export class apiService { /* all other code is left as is,just change the get method to also accept data via the params. If null is passed in then it is ignored. */ get(url,failure) { return this.$http({ url: url,config: config,params: data,method: "GET" }) .then(result => { this.handleResponse(result,failure) }); } }
在通话中我们只需要从post更改为get,它应该可以工作.
// only change from post to get onCompanyChanged(selectedCompany,companyName) { this.apiService.get('/api/Dashboard/GetAssetListByCompany',response => { this.assetListviewmodel = response.data.data; },response => { this.notificationService.displayError(response.data.message); }); }
编辑 – 这很灵活
更重要的是,这种设计在角度方面是灵活的.如果您扩展MVC操作或具有采取其他参数的各种操作,则无需执行任何其他更改即可运行.例:
[HttpGet] [Route("GetSomethingElseFromServer")] public IActionResult GetSomethingElseFromServer([FromQuery]int companyId,[FromQuery]string assetName,[FromQuery]string companyModelNumber) // use FromQuery
对你的角度api的调用将是
this.apiService.get('/api/Dashboard/GetSomethingElseFromServer',{ companyId: companyId,assetName: somePassedInAssetNameVar,companyModelNumber: somePassedInModelNumber }
编辑 – 您也可以发送数组
要回答关于如何将多个基元类型作为数组发送的问题,您可以这样做.同样,这假设它不是您要发送的复杂类型,但是,例如,公司ID列表.
c#代码
[HttpGet] [Route("GetAssetListByCompany")] public IActionResult GetAssetListByCompany([FromQuery]int[] companyIds) // use an array of int ie. int[]. i changed the variable name to make it clear there can be more than 1
Angular调用,注意没有必要更改服务
onCompanyChanged(selectedCompany,{ "companyIds[]": [id1,id2,id3] },// note the name is Now enclosed in quotes,made plural,and includes []. The value is an array response => { this.assetListviewmodel = response.data.data; },response => { this.notificationService.displayError(response.data.message); }); }
编辑 – 如果你想要POST
您目前只发送一个原始字段,因此POST中的MVC框架无法正确反序列化.您需要将参数包装在视图模型中,将其作为查询字符串部分发送,或将其作为表单字段值发送.这是带有查询字符串部分的POST,它可以正常工作.
选项1
将其附加到URL
[HttpPost] // change to HttpGet [Route("GetAssetListByCompany")] public IActionResult GetAssetListByCompany([FromQuery] int companyId) // use FromQuery
角度呼叫
this.apiService.post('/api/Dashboard/GetAssetListByCompany/?companyId=' + selectedCompany.id +,null,// the rest of the code remains unchanged so I did not include it
选项2
扩展apiService以获取params对象,以便它可以构建您的查询.无论哪种方式,你都会遇到调用者不得不对http调用有所了解.
this.apiService.post('/api/Dashboard/GetAssetListByCompany',{companyId: selectedCompany.id},// the rest of the code remains unchanged so I did not include it post(url,params,failure) { return this.$http({ url: url,data: data,params: params,method: "POST" }) .then(result => { this.handleResponse(result,failure) }); }
选项3
更新视图模型以采用复杂类型,这不需要更改角度代码.
public class ListByCompanyModel { public int CompanyId {get;set;} } [HttpPost] // change to HttpGet [Route("GetAssetListByCompany")] public IActionResult GetAssetListByCompany([FromBody] ListByCompanyModel model) // use FromQuery
angularjs – Angular POST to Web API不传递数据
我正在发布一个方法,该方法将返回系统中实体的一些搜索结果.它看起来像这样:
public IEnumerable<dynamic> Post(string entity,FormDataCollection parameters) { // entity is passed on the route. // parameters contains all the stuff I'm trying to get here. }
如果我使用jQuery.post调用该方法:
$.post('api/search/child',{where : 'ParentID = 1'},function(d){ foo = d });
它运作正常,并返回我期望的.
我在我的角度应用程序中提供了一个类似的调用服务:
$http.post('api/search/child',{ where: 'parentID = ' + parent.ID }) .success(function (data,status,headers,config) { // etc. })
但是当它在服务器上点击我的“Post”方法时,“paramters”为空.
经过一些谷歌搜索后,我尝试添加一个内容类型的标题,以确保它作为JSON传递,并尝试JSON.stringify-ing和$.param() – “数据”参数,但没有做任何事情(和从我所读到的那些不应该是必要的.)我在这里做错了什么?谢谢你的帮助!
更新:
这是来自(工作)jQuery示例的原始请求:
POST http://localhost:51383/api/search/child HTTP/1.1 Accept: */* Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Referer: http://localhost:51383/mypage.aspx Accept-Language: en-US Accept-Encoding: gzip,deflate User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko Host: localhost:51383 Content-Length: 23 DNT: 1 Connection: Keep-Alive Pragma: no-cache Cookie: (etc) Authorization: (etc) where=ParentID+%3D+1
来自(失败的)Angular样本的原始请求:
POST http://localhost:51383/api/search/parent HTTP/1.1 Content-Type: application/json;charset=utf-8 Accept: application/json,text/plain,*/* Referer: http://localhost:51383/mypage.aspx Accept-Language: en-US Accept-Encoding: gzip,deflate User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko Connection: Keep-Alive Content-Length: 27 DNT: 1 Host: localhost:51383 Pragma: no-cache Cookie: (etc) {"where":"scorecardID = 1"}
很奇怪.即使我将’json’数据类型参数添加到jQuery调用的末尾,它仍然会创建www-form-urlencoded请求.那是有效的.我的Web API应用程序已经为JSON设置(但感谢Dalorzo).
解决方法
System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); config.Formatters.Insert(0,new System.Net.Http.Formatting.JsonMediaTypeFormatter());
只有设置了正确的格式化程序,Content-Type = application / json才有效.
您也可以尝试在参数类型旁边使用[FromBody].
angularjs – Angular – > Web Api 2:“没有’Access-Control-Allow-Origin’标题”
我已将我的CORS属性添加到我的WebApiConfig类:
public static void Register(HttpConfiguration config) { var cors = new EnableCorsAttribute("http://localhost:51407","*","*"); config.EnableCors(cors);
但是每当我发送一个正确包含的Ajax请求(使用angularJS)时
Origin: http://localhost:51407
我收到错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:51407' is therefore not allowed access.
可能是什么问题?
解决方法
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="your_clientWebUrl" /> </customHeaders> </httpProtocol> </system.webServer>
今天关于angularJs – 405方法不允许在WebAPI2(OWIN)和angularjs表达式中不能使用的运算符的讲解已经结束,谢谢您的阅读,如果想了解更多关于angularjs – Angular 1.2不再允许在同一个元素上使用多个隔离的范围指令?、angularjs – Angular JS MVC Web API模型/参数不绑定.NET Core、angularjs – Angular POST to Web API不传递数据、angularjs – Angular – > Web Api 2:“没有’Access-Control-Allow-Origin’标题”的相关知识,请在本站搜索。
本文标签: