的ASP.NET Web API - 阿贾克斯PUT - 405不允许的方法(实体框架) [英] ASP.NET Web API - Ajax PUT - 405 Method Not Allowed (Entity Framework)

查看:202
本文介绍了的ASP.NET Web API - 阿贾克斯PUT - 405不允许的方法(实体框架)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图把一个更新使用JSON到通过jQuery的Ajax功能的ASP.NET Web API的用户。我不断收到一个 405(方法不允许)来自服务器的响应。我曾经尝试过的一切,包括web.config中禁用WebDAV模块并添加访问控制允许来源头到我的web.config为好。

我以前使用ADO模型的DbContext生成数据库第一种方法。该控制器还通过ASP.NET创建时产生的。我想他们应该工作。

我曾经尝试都PUT和POST无济于事。我不知道我做错了。

我的JS code:

 函数UpdateUserLoginTime(用户){   $ .getScript(SRC / JS / datetimeutils.js);
   VAR URL =htt​​p://foo.bar.com:8081/api/user/\".concat(user.ID);   无功电流= CurrentDateTime();   $阿贾克斯({
       网址:网址,
       输入:'把',
       数据:JSON.stringify({LastLoginDate:当前})
       数据类型:JSON
       的contentType:应用/ JSON的;字符集= UTF-8,
       跨域:真实,
       成功:功能(数据){
           警报('成功更新用户的登录时间');
       },
       错误:函数(){
           警报('更新登录时间错误');
       }
   });
}

有关的帖子,我想JSON.stringify(用户)以及(不上的网址CONCAT(ID))。

下面是我的ASP.NET控制器code:

  // PUT API /用户/ 5
    公众的Htt presponseMessage PutUser(字符串ID,用户的用户)
    {
        如果(ModelState.IsValid&安培;和ID == user.ID)
        {
            db.Entry(用户).STATE = EntityState.Modified;            尝试
            {
                db.SaveChanges();
            }
            赶上(DbUpdateConcurrencyException)
            {
                返回Request.CreateResponse(的HTTPStatus code.NotFound);
            }            返回Request.CreateResponse(的HTTPStatus code.OK);
        }
        其他
        {
            返回Request.CreateResponse(的HTTPStatus code.BadRequest);
        }
    }    // POST API /用户
    公众的Htt presponseMessage PostUser(用户用户)
    {
        如果(ModelState.IsValid)
        {
            db.Users.Add(用户);
            db.SaveChanges();            HTT presponseMessage响应= Request.CreateResponse(的HTTPStatus code.Created,用户);
            response.Headers.Location =新的URI(Url.Link(DefaultApi,新{ID = user.CAC}));
            返回响应;
        }
        其他
        {
            返回Request.CreateResponse(的HTTPStatus code.BadRequest);
        }
    }

我的配置:

 < system.webServer>
<验证validateIntegratedModeConfiguration =FALSE/>
<模块runAllManagedModulesForAllRequests =真正的>
  <清除NAME =WebDAVModule/>
< /模块>
<&处理GT;
  <清除NAME =ExtensionlessUrlHandler-ISAPI-4.0_32bit/>
  <清除NAME =ExtensionlessUrlHandler-ISAPI-4.0_64bit/>
  <清除NAME =ExtensionlessUrlHandler - 集成 - 4.0/>
  <添加名称=ExtensionlessUrlHandler-ISAPI-4.0_32bitPATH =*。动词=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS模块=IsapiModulescriptProcessor ​​=%WINDIR%\\ Microsoft.NET \\框架\\ v4.0.30319 \\ ASPNET_ISAPI.DLLpreCondition = classicMode,runtimeVersionv4.0,bitness32responseBufferLimit =0/>
  <添加名称=ExtensionlessUrlHandler-ISAPI-4.0_64bitPATH =*。动词=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS模块=IsapiModulescriptProcessor ​​=%WINDIR%\\ Microsoft.NET \\ Framework64 \\ v4.0.30319 \\ ASPNET_ISAPI.DLLpreCondition = classicMode,runtimeVersionv4.0,bitness64responseBufferLimit =0/>
  <添加名称=ExtensionlessUrlHandler - 集成 - 4.0PATH =*。动词=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONSTYPE =System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
< /处理器>
< httpProtocol>
  < customHeaders>
    <添加名称=访问控制允许来源VALUE =*/>
  < / customHeaders>
< / httpProtocol>

我RouteConfig:

 公共类RouteConfig
{
    公共静态无效的RegisterRoutes(RouteCollection路线)
    {
        routes.IgnoreRoute({}资源个.axd / {*} PATHINFO);        routes.MapRoute(
            名称:默认,
            网址:{控制器} / {行动} / {ID}
            默认:新{控制器=家,行动=索引,ID = UrlParameter.Optional}
        );
    }
}


解决方案

您需要使Web API CORS,否则发送请求时,你总能得到响应405不会允许。 看看这个

I am trying to PUT an update to a user using JSON to ASP.NET Web API via JQuery's Ajax function. I keep getting a 405 (Method not Allowed) response from the server. I have tried just about everything, including disabling the WebDAV module in web.config and adding Access-Control-Allow-Origin headers to my web.config as well.

I used the database-first approach using ADO Model and DbContext generation. The controllers were also generated by ASP.NET upon creation. I assume they should work.

I have tried both PUT and POST to no avail. I have no idea what I am doing wrong.

My JS code:

function UpdateUserLoginTime(user) {

   $.getScript("src/js/datetimeutils.js");
   var url = "http://foo.bar.com:8081/api/user/".concat(user.ID);

   var current = CurrentDateTime();

   $.ajax({
       url: url,
       type: 'PUT',
       data: JSON.stringify({"LastLoginDate" : current}),
       datatype: "json",
       contentType: "application/json; charset=utf-8",
       crossDomain: true,
       success: function (data) {
           alert('User login time updated sucessfully');
       },
       error: function () {
           alert('Update login time error');
       }
   });
}

For the post, I tried JSON.stringify(user) as well (without concat(ID) on url).

Here is my ASP.NET Controller code:

 // PUT api/User/5
    public HttpResponseMessage PutUser(string id, User user)
    {
        if (ModelState.IsValid && id == user.ID)
        {
            db.Entry(user).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

    // POST api/User
    public HttpResponseMessage PostUser(User user)
    {
        if (ModelState.IsValid)
        {
            db.Users.Add(user);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.CAC }));
            return response;
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

My config:

<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule"/>
</modules>
<handlers>
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

My RouteConfig:

 public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

解决方案

You need enable CORS for web api, else when send a request, you always get response 405 not allow. Look this.

这篇关于的ASP.NET Web API - 阿贾克斯PUT - 405不允许的方法(实体框架)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆