简体   繁体   English

从HttpContext Angular和Web API获取数据

[英]Get data from HttpContext Angular and Web API

In the angular controller I have this code to transfer $scope.myModel to a Web API controller: 在角度控制器中,我有以下代码将$ scope.myModel传输到Web API控制器:

$scope.upload[index] = $upload.upload({
  url: settings.constants.uploadURL,
  headers: { 'myHeaderKey': 'myHeaderVal' },
  data: { model: $scope.myModel },
  file: $file,
  fileFormDataName: 'myFile'
}).then(function (response) { ...

The Web API controller post method looks like this Web API控制器的post方法如下所示

public HttpResponseMessage Post()
{
  return UploadFile(HttpContext.Current);
}

How do I get the data: model from out from the HttpContext?? 我如何获取数据:从HttpContext中提取模型?

WebAPI is not designed to be used in that fashion. WebAPI并非旨在以这种方式使用。 Specifically, it is usually bad practice to refer to HttpContext.Current from within a WebAPI controller method. 具体来说,从WebAPI控制器方法中引用HttpContext.Current通常是一种不好的做法。 If you did want to check the request or response, you should refer to them by the properties of the ApiController base class, see the msdn docs . 如果确实要检查请求或响应,则应通过ApiController基类的属性来引用它们,请参阅msdn docs

Usually, people prefer model binding for situations like this. 通常,人们喜欢在这种情况下进行模型绑定。 Suppose you had in js: 假设您使用过js:

{
   foo: "bar"
}

You should declare a class in C# that maps to it: 您应该在C#中声明一个映射到它的类:

public class MyRequestModel
{
   public string Foo { get; set; }
}

And by declaring your API method: 并通过声明您的API方法:

public HttpResponseMessage Post(MyRequestModel mdl)
{
// do stuff, mdl.Foo will have "bar" in it magically
}

This results in more object-oriented ways of transferring data from javascript to C#. 这导致了更多面向对象的方式将数据从javascript传输到C#。 It's more typesafe because you can be guaranteed that the Foo property in C# will have a string , or an int , or whatever you declare it to be as opposed to parsing the request yourself. 类型安全性更高,因为可以保证C#中的Foo属性将具有stringint或任何您声明为与自己解析请求相对的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM