Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Web API的删除操作方法未获取触发器_C#_Asp.net Mvc_Asp.net Mvc 4_Model View Controller_Asp.net Web Api - Fatal编程技术网

C# Web API的删除操作方法未获取触发器

C# Web API的删除操作方法未获取触发器,c#,asp.net-mvc,asp.net-mvc-4,model-view-controller,asp.net-web-api,C#,Asp.net Mvc,Asp.net Mvc 4,Model View Controller,Asp.net Web Api,我的项目中有一个WebAPI控制器,如下所示 public class EmployeeController : ApiController { static readonly IEmployeeRepository repository = new EmployeeRepository(); // GET api/<controller> [HttpGet] public object Get() { var queryStr

我的项目中有一个WebAPI控制器,如下所示

public class EmployeeController : ApiController
{
    static readonly IEmployeeRepository repository = new EmployeeRepository();
    // GET api/<controller>
    [HttpGet]
    public object Get()
    {
        var queryString = HttpContext.Current.Request.QueryString;
        var data = repository.GetAll().ToList();
        return new { Items = data, Count = data.Count() };
    }

    public Employee GetEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return emp;
    }

    // POST api/<controller>
    public HttpResponseMessage PostEmployee(Employee emp)
    {
        emp = repository.Add(emp);
        var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

        string uri = Url.Link("Employee", new { id = emp.EmployeeID });
        response.Headers.Location = new Uri(uri);
        return response;
    }
     [HttpPut]
    // PUT api/<controller>
    public void PutEmployee(Employee emp)
    {

        if (!repository.Update(emp))
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

    }
    [HttpDelete]
     public void DeleteEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        repository.Remove(id);
    }
}
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        GlobalConfiguration.Configure(WebApiConfig.Register);

        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);



    }
和global.cs文件,如下所示

public class EmployeeController : ApiController
{
    static readonly IEmployeeRepository repository = new EmployeeRepository();
    // GET api/<controller>
    [HttpGet]
    public object Get()
    {
        var queryString = HttpContext.Current.Request.QueryString;
        var data = repository.GetAll().ToList();
        return new { Items = data, Count = data.Count() };
    }

    public Employee GetEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return emp;
    }

    // POST api/<controller>
    public HttpResponseMessage PostEmployee(Employee emp)
    {
        emp = repository.Add(emp);
        var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

        string uri = Url.Link("Employee", new { id = emp.EmployeeID });
        response.Headers.Location = new Uri(uri);
        return response;
    }
     [HttpPut]
    // PUT api/<controller>
    public void PutEmployee(Employee emp)
    {

        if (!repository.Update(emp))
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

    }
    [HttpDelete]
     public void DeleteEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        repository.Remove(id);
    }
}
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        GlobalConfiguration.Configure(WebApiConfig.Register);

        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);



    }
有一次我删除了这个员工

General:

Request URL:http://localhost:63187/api/Employee/2
Request Method:DELETE
Status Code:404 Not Found
Remote Address:[::1]:63187
响应头

   Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Cache-Control:no-cache
Content-Length:204
Content-Type:application/json; charset=utf-8
Date:Thu, 30 Mar 2017 12:00:21 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcU2FtcGxlXE1WQ1xEYXRhTWFuYWdlclxBZGFwdG9yc1xTYW1wbGVcYXBpXEVtcGxveWVlXDI=?=
请求头

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:1
Content-Type:application/json; charset=UTF-8
DataServiceVersion:2.0
Host:localhost:63187
MaxDataServiceVersion:2.0
Origin:http://localhost:63187
Referer:http://localhost:63187/CRUDRemote/Remove
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest
请求有效载荷

2
我的ajax请求将如下所示

beforeSend:function (),
contentType:"application/json; charset=utf-8",
data:"2",
error:function (e),
success:function (),
type:"DELETE",
url:"/api/Employee/2",

当我在IIS下托管的新WebAPI项目中犯错误时,PUT和DELETE方法会立即返回404个错误<必须先编辑IIS的code>applicationhost.config,然后才能使用它们

%userprofile%\documents\iisexpress\config\applicationhost.config

寻找

<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
建议,您必须注释掉同一文件中的以下行

<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
<add name="WebDAVModule" /> 
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />

对于我来说,在web.config中添加以下内容一直有效。在远程服务器上使用WebAPI时,默认情况下不允许删除

   <system.webServer>
    <modules>
    <remove name="WebDAVModule"/>
    </modules>
    <handlers>
    <remove name="WebDAV" />
    <remove name="ExtensionlessUrl-Integrated-4.0" />
    <add name="ExtensionlessUrl-Integrated-4.0"
    path="*."
    verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
    type="System.Web.Handlers.TransferRequestHandler"
    preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    </system.webServer>

最后我发现了问题,我在Global.cs和WebApiConfig中犯了错误

     public static void Register(HttpConfiguration config)
    {
        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
                        name: "Employee",
                        routeTemplate: "api/{controller}/{id}",
                        defaults: new { id = RouteParameter.Optional }
                    );
        //config.EnableQuerySupport();
    }
更新的Global.cs文件

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        //GlobalConfiguration.Configure(WebApiConfig.Register);

        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);


    //    WebApiConfig.Register(GlobalConfiguration.Configuration);
    }
和WebApiConfig

     public static void Register(HttpConfiguration config)
    {
        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
                        name: "Employee",
                        routeTemplate: "api/{controller}/{id}",
                        defaults: new { id = RouteParameter.Optional }
                    );
        //config.EnableQuerySupport();
    }

现在,已触发删除操作

看看这里,看看它是否可以解决您在调用api、MVC应用程序或Ajax请求时遇到的问题?可能是承载应用程序的Web服务器不支持该方法吗?请指定承载服务的服务器。IIS?自我主持?嗨,Sulay,我是根据Ajax请求打电话来的