在同一个http服务器上托管Aurelia CLI应用程序和WebApi服务

时间:2016-07-31 22:21:11

标签: asp.net-web-api cors aurelia aurelia-framework

如何进行配置,以便<button onclick='addHouseHolds(5, ["Smith", "Black", "Johnson","Williams","Jones"], [0,1,2,3,4] )'>Click me</button> 在同一个http服务器上启动并托管Aurelia app和Web API服务?

联系人管理器非常棒,我完全理解为什么它会嘲笑Web服务,但你无法构建这样的真实应用程序。

是否有设置网络服务的演练?事件如果只是从文件读取一些JSON并提供它,真正的问题是如何设置在同一http服务器上运行的Web服务来处理XSS问题。

未完整演练如何创建http服务器实例的节点代码的某些指导。 au run和CLI很棒,但它们隐藏了很多重要信息。

1 个答案:

答案 0 :(得分:2)

简短的回答是你不要这样做。

虽然理论上可行,但这比仅解决CORS问题和为Web API使用单独的服务器要求更高,更有用。只有当你知道如何在客户端和服务器上处理CORS时,这是显而易见的,如果你知道它不会让你想到这个问题。

为了帮助这条令人沮丧的标志性道路上的迷失,以下是如何在9000上使用Aurelia客户端处理IIS7 MVC / WepApi2的CORS。

服务器

将此作为Web API项目根目录<system.webServer>文件的web.config部分的子项。

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

对于此示例,http://testserver/DAL3/api/Form处有一个Web API服务,其中一个方法必须发布。

这是一个支持班级

  public class JsonRequest
  {
    public int UID { get; set; }
    public string Command { get; set; }
    public string Raw { get; set; }
  }

这就是网络服务的样子。有一个支持它的LINQ2SQL模型,为简洁起见,我省略了它。

using Newtonsoft.Json;
using System.Linq;
using System.Reflection;
using System.Web.Http;

namespace DAL3.Controllers
{
  public class FormController : ApiController
  {

    // POST: api/Form
    public object Post([FromBody]JsonRequest jsr)
    {
      var T = GetType();
      var M = T.GetMethod(jsr.Command, BindingFlags.NonPublic | BindingFlags.Instance);
      var parms = new object[] { jsr.UID, jsr.Raw };
      if (M == null) return string.Format("M is null (\"{0}\")",jsr.Command);
      if (parms == null) return "parms is null";

      return M.Invoke(this, parms);
    }

    object Get(int UID, string Raw)
    {
      var dc = new Models.FormsDataContext();
      if (string.IsNullOrEmpty(Raw))
      {
        return dc.Forms.Where(x => x.FormEngine == true);
      }
      else
      {
        var id = JsonConvert.DeserializeObject<GetParams>(Raw).Id;
        return dc.Forms.Where(x => x.FormID == id);
      }
    }
  }
  //this class describes how to parse the parameters for Get
  class GetParams
  {
    public int Id { get; set; }
  }
  //if you defined some other method Quux that takes parameters 
  //create a QuuxParams class that matches what JS sends
}

所有这些反思业务都允许您在Command中指定方法名称,并在Raw中将您喜欢的任何内容传递给它。 UID是用户标识符。

这样做可以让您将CORS合规性与请求分开,并自动对Raw中的任何内容进行编码。哪个应该命名为Parameters,但无论如何。现在你知道如何把它们放在一起了。

客户端

将bash与pwd设置为应用的根目录:

npm i aurelia-http-client --save

然后将其添加到aurelia.json中的供应商包依赖项中。您不需要一个对象,只需要带有尾随逗号的双引号中的名称,以适用于有效的JSON语法。

在您的代码中,您需要导入它。

import {HttpClient} from 'aurelia-http-client';

以下是名为DAL3的Web应用程序中名为Form的Web API服务的帖子示例,名为testserver。

let foo = {
  UID: 18974,
  Command: "Get",
  Raw: null
}

let content = "UID=" + foo.UID + "&Command=" + foo.Command + "&Raw=" + JSON.stringify(foo.Raw)

let client = new HttpClient();

let req = client.createRequest("http://testserver/DAL3/api/Form")
 .asPost()
 .withHeader("Content-Type","application/x-www-form-urlencoded")
 .withContent(content)
 .send()
 .then(res => {
   console.log("Hurrah we have a response!");
 });

注意事项

以下任何一项都会导致&#34;预检&#34;请求使用动词OPTIONS,这将导致失败。

  • 添加非标准标题
  • 使用text/plainapplication/x-www-form-urlencoded
  • 以外的内容类型
  • 使用GET或POST以外的动词

编码内容

对象foo根目录下的三个属性是URL编码的,并用&符号分隔,如上面的示例代码所示。 Raw可以包含一个对象,甚至可以包含有向对象的非循环图。 JSON.stringify正确处理两者。 Null将解析为空字符串,但URL编码的解码将产生空值,因此很好;重要的是Raw参数应该存在以满足另一端的Web API签名匹配。