【问题标题】:POST method not allowed angularJS, .NET不允许使用 POST 方法 angularJS、.NET
【发布时间】:2015-05-22 20:14:45
【问题描述】:

我正在尝试使用基本的 CRUD 操作制作简单的 UI。 GET 方法正常工作,但我无法使 POST 方法工作(但是,当我想通过 fiddler 测试 POST 方法时,它可以工作,数据已正确插入数据库中......)

我的应用分为多个层。 API 控制器位于一层,angularJS 代码和视图位于第二层(Web 层)。 Web 层运行在 50004 端口,API 层运行在 54927 端口。所以我在angular文件中写了这段代码:

var serviceBase = 'http://localhost:54927/';
onlineTesting.constant('ngAuthSettings', {
    apiServiceBaseUri: serviceBase,
    clientId: 'onlineTesting'
});

我在网上发现我必须启用 cors 并在我的 webconfig 文件中添加一些代码,您可以在下面看到。

这就是我的 angular 文件中的内容:

var _addCategory = function (category) {
    $http.post(serviceBase + 'api/Categories', category).then(function (response) {
        return response;
    });
};

api 控制器:

[RoutePrefix("api/Item")]
public class CategoriesController : ApiController
{
    ICategoriesRepository _categoriesRepo;
    ICategoriesServices _categoriesServices;

    public CategoriesController()
    {
        _categoriesRepo = new CategoriesRepository();
        _categoriesServices = new CategoriesServices();
    }

    public HttpResponseMessage Post(Categories category)
    {
        var result = _categoriesServices.AddCategory(category.CategoryType);

        if (result == category.CategoryId)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, category);
            return response;
        }
        else
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

    }
    public IHttpActionResult Get()
    {
        var categories = _categoriesServices.GetCategories();

        return Ok(categories);
    }
    public IHttpActionResult Get(int id)
    {
        var categories = _categoriesServices.GetCategoryById(id);

        return Ok(categories);
    }
    public IHttpActionResult Delete(int categoryId)
    {
        var result = _categoriesServices.RemoveCategoryById(categoryId);

        if (result)
            return Ok();
        else
            return BadRequest("Item ID doesn't exist in database");
    }
    public IHttpActionResult Put(Categories category)
    {
        var result = _categoriesServices.UpdateCategory(category); 

        if (result)
            return Ok();
        else
            return BadRequest("Category has not been updated, please check            your category.");
    }
}

我也在我的 webconfig 文件中添加了这个:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

这是我调用 addCategory 方法的 html 文件的一部分:

div id="registration-form">
<h3 class="crudheader">Add new category</h3>
<div class='fieldset'>
    <form action="#" method="post" data-validate="parsley">
        <div class='row'>
            <input type="text" maxlength="1000" data-required="true" placeholder="Enter new category"
                   data-error-message="Category is required" data-ng-model="category.categoryType">
            <h5 data-ng-model="message">Place your text here ({{ message }})</h5>
        </div>
        <button type="button" data-ng-click="addCategory(category)">Submitt</button>
    </form>
</div>

当我点击提交按钮时,我总是在 Inspect 元素的控制台选项卡中收到这些消息: 远程地址:127.0.0.1:8888

常规

请求网址:myURL(使用端口 54927)

请求方法:OPTIONS

状态码:405 方法不允许

响应标头

HTTP/1.1 405 方法不允许

缓存控制:无缓存

编译指示:无缓存

允许:POST、GET、PUT

内容类型:应用程序/json;字符集=utf-8

过期:-1

服务器:Microsoft-IIS/8.0

X-AspNet-版本:4.0.30319

X 源文件: =?UTF-8?B?QzpcVXNlcnNcQVBJIExhYlxEZXNrdG9wXE9ubGluZVRlc3RpbmdcTmV3T25saW5lVGVzdGluZ1xBcGlMYWIuT25saW5lVGVzdGluZy5BcGlMYXllclxhcGlcQ2F0ZWdvcmllcw==?=

X-Powered-By:ASP.NET

访问控制允许来源:*

Access-Control-Allow-Headers:Origin、X-Requested-With、Content-Type、 接受

访问控制允许方法:GET、POST、PUT、DELETE、OPTIONS

日期:格林威治标准时间 2015 年 3 月 19 日星期四 15:08:24

内容长度:76

请求标头

选项http://localhost:54927/api/Categories HTTP/1.1

主机:本地主机:54927

代理连接:保持活动

访问控制请求方法:POST

来源:myURL(带有 url 50004)

用户代理:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,如 Gecko)Chrome/41.0.2272.89 Safari/537.36

Access-Control-Request-Headers:接受,内容类型

接受:/

Referer:myUrl(使用端口 50004)

接受编码:gzip、deflate、sdch

接受语言:en-GB,en-US;q=0.8,en;q=0.6

【问题讨论】:

  • 你检查我的答案了吗?
  • @pankajparkar,嘿伙计,抱歉重播晚了,我试过你的方法,仍然出现同样的错误

标签: .net angularjs http


【解决方案1】:

除了前面提到的安装 CORS 包的内容外,请确保包含以下行, [EnableCors(来源:“http://mywebclient.azurewebsites.net”,标题:“”,方法:“”)] 在 API 控制器中。

示例:

[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

参考:

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

【讨论】:

    【解决方案2】:

    我找到了解决方案。我通过 PM 安装了 CORS 包。然后在 API 层的 WebApiConfig 文件中添加了 config.EnableCors(),并从 web.config 文件中删除了 customHeaders。

    原因是我不应该同时在 web.config 和“config.EnableCors()”中有这两行,因为 config.EnableCors() 还允许标头和方法,如果两者都在代码,它们会发生某种冲突,然后我的 POST 将无法正常工作。

    【讨论】:

      【解决方案3】:

      我相信您需要为category 执行JSON.stringfy(),这将stringify 对象并传递给控制器​​操作并从表单中删除操作和方法属性。

      代码

      var _addCategory = function (category) {
          $http.post(serviceBase + 'api/Categories', JSON.stringfy(category)).then(function (response) {
              return response;
          });
      };
      

      在 HTML 上,在表单元素级别使用 ng-submit 方法

      HTML

      <form data-validate="parsley" data-ng-submit="addCategory(category)">
          <div class='row'>
              <input type="text" maxlength="1000" data-required="true" placeholder="Enter new category"
                     data-error-message="Category is required" data-ng-model="category.categoryType">
              <h5 data-ng-model="message">Place your text here ({{ message }})</h5>
          </div>
          <button type="submit">Submit</button>
      </form>
      

      更新

      您也可以在动作参数中添加 [FromBody]

      代码

      public HttpResponseMessage Post([FromBody] Categories category) {
          var result = _categoriesServices.AddCategory(category.CategoryType);
      
          if (result == category.CategoryId) {
              HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, category);
              return response;
          } else
              return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
      
      }
      

      希望对您有所帮助,谢谢。

      【讨论】:

      猜你喜欢
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 2016-02-15
      • 2014-04-18
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      相关资源
      最近更新 更多